Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple inheritance and pointer implementation

Tags:

c++

Given the following code:

namespace Example1 {

class A {
public:
    A() {}
    virtual ~A() {}
private:
    float data_A;
};

class B {
public:
    B() {}
    virtual ~B() {}
protected:
    float data_B;
};

class Derived : public A, public B {
public:
    Derived() {}
    virtual ~Derived() {}
protected:
    float data_Derived;
};

}

int main (void)
{
using namespace Example1;
B* pb = new Derived;
delete pb;
}

pb should now point to the B part of the Derived object. But the derived object also derives from A, means it has A sub-object.. and that A sub-object should be "first" because the Derived class first inherits from A.

How does the compiler approves that? what does it add in order to make it work correctly?

and also, how does it free the memory correctly when deleting the object?

like image 278
Rouki Avatar asked Apr 26 '26 02:04

Rouki


1 Answers

The short answer is: By magic.

The medium answer is: It's not for you to worry about. The Standard says that this works, and it's up to the compiler to figure out a way to make it work.

The long answer: Since this depends on your compiler, read up your compiler's documentation! Many C++ compilers implement the Itanium C++ ABI, so that's a start. As part of polymorphic inheritance, each class usually has a so-called vtable, which stores a bunch of function pointers, but it also stores RTTI information and joined virtual-destruction and memory-deallocation logic. Think about it: delete pb; doesn't just have to call the right destructors in the right order, but it also has to pass the correct pointer to the deallocation function. All this information is included in the various vtables of the class hierarchy.

like image 72
Kerrek SB Avatar answered Apr 28 '26 17:04

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!