Question

I've created two classes, A and B. B contains a pointer to A, but never initializes A. However, I am able to call the functions of A without ever initializing A. How/Why is this possible?

 class A
{
public:
    void Test() {
        printf("Test from A\n");
    }
};


class B
{

public:
    B() {
    }
    ~B() {
    }
    void T() {
        a->Test();
    }
private:
    A* a;
};


int main() {

    B b;
    b.T();
    /*
    B* b;
    b->T();    //This does not work, as expected. So why can I call a->Test via b.T(), and have that work when a was never initialized?
    */

    system("PAUSE");
    return 0;
}
Was it helpful?

Solution 2

While the value of your a* is undefined, I believe the behavior of this code is actually defined.

The Test function's real header is going to be generated as: void Test(A* this); Meaning - it's a simple C function that gets a struct's pointer as its first parameter.

Since your b object has an initialized a object in it (initialized randomly by whatever resides in the memory it points to), when you call for a->test() you will call the Test function correctly (with the same random as the value of "this"). Since you perform no use of the "this" pointer in Test, it will actually work as expected.

OTHER TIPS

It is because compiler, internally, transforms a call like a->Test() into slightly different form:

A::Test(a);

As you can see, the function it's calling is just an address and the object it's called on is passed as an argument, which can be nullptr/uninitialized/anything.

For virtual functions, it will be almost the same, with a bit more details involved:

a->vtbl[0](a);

Where vtbl is a table of virtual function pointers, initialized usually at object construction time, but it's offset is usually known at compile time, that's why a compiler won't really have any troubles "calling" it on an object that doesn't exist - it will just read garbage from random memory location and use that happily.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top