About pointers and inheritance

]I just wanted to clarify that my thought about how stuff implicitly works is right as it's bugging me.

Simply enough, two classes of A and B. B is the derived class and A is the base class.

If I create a pointer as such:

1
2
B bobj;
A * aptr = &bobj;



1. The pointer is pointing to an actual location in memory where the A "part" of the derived object is right? Meaning, the pointer is not just an interface to abide by (this also applies to references).

2. Based on the above, within each member function of a class the "this" pointer is converted a pointer to that class. So if I call a function within A from bobj, the "this" pointer will now be A*?

3. Finally, if I call a function in the derived (B) and do a dynamic_cast<void*> then the pointer returned will now be a pointer to the A part of B.
Last edited on
1) Basically. Although you cannot call B class things from that pointer, you will get an error.

2) Well, you can only call the functions/access the members of an A class from that pointer, so yes.

3) What do you mean?
I mean this:

1
2
3
4
5
6
7
function_in_B()
{
   dynamic_cast<void*>(this);
}

B bobj;
bobj.function_in_B();


That dynamic cast in function_in_B(), the this pointer is converted from being a pointer to B to now being a pointer to highest base class in memory which in this case is its base of A.

One more thing:

1
2
A * aptr = &bobj;
delete aptr;


So when I call delete on aptr above, the reason why implicitly we need virtual functions is that we are only pointing to the A portion of bobj. Thus, we need virtual destructors. If that's good then I got it.
That function does nothing. A cast only temporarily changes how the compiler treats a variable. And casting to a void pointer means you cannot call any member functions nor dereference it, as you have casted it to a generic pointer type, with no information about how to read the data at that memory address.

Your understanding of the concept of virtual destructors seems fine, but your use in that particular situation (example) is wrong. This is how you would do it:
1
2
A* aptr = new B; // create a new B, but refer to it with an A ptr
delete aptr; //virtual destructors will ensure we properly delete the B portion as well 
Topic archived. No new replies allowed.