I'm using multiple inheritance for some stuff, and I'm wondering if anyone could explain how it is generally implemented. I don't quite get how some things are possible.
Suppose I have the following:
class BaseA {
public:
int a;
};
class BaseB {
public:
int b;
};
class DerivedAB : public BaseA, public BaseB {
public:
void setAB() {
a = 10;
b = 20;
}
};
First of all, in memory, what is the layout of DerivedAB? Is it BaseA followed by BaseB?
I did the following test:
DerivedAB * derived = new DerivedAB();
derived->setAB();
BaseA * aPtr = derived;
BaseB * bPtr = derived;
std::cout << "Value of a from aPtr: " << aPtr->a << '\n';
std::cout << "Value of b from bPtr: " << bPtr->b << '\n';
std::cout << "Location of derived: " << derived << '\n';
std::cout << "Location of aPtr: " << aPtr << '\n';
std::cout << "Location of bPtr: " << bPtr << '\n';
DerivedAB * derivedPtr = (DerivedAB*)bPtr;
std::cout << "Value of b from derivedPtr: " << derivedPtr->b << '\n';
delete bPtr;
I create a new DerivedAB and then point to it from a pointer of each base class. The output I get (which is expected) is as follows:
Value of a from aPtr: 10
Value of b from bPtr: 20
Location of derived: 00035F98
Location of aPtr: 00035F98
Location of bPtr: 00035F9C
Value of b from derivedPtr: 20
When (implicitly) casting from DerivedAB* to BaseB*, the location of bPtr was offset by 4 from the location of derived. How does delete work with this? In my test, I new a DerivedAB and I delete a BaseB. How is it determined that the object I should be deleting is actually 4 memory locations back?
Basically, some info on how this is implemented would be useful because I don't want to mess something up because I don't understand it. Thanks.