You can think of a
derived class as a class that "copies" (inherits) the definition of its
base class and
extends that definition. The derived class has an inheritance relationship to its base class, but it still is a class of its own. That's different from, e.g. JavaScript, where objects
do contain a reference to their "prototype" object.
An instance (object) of the
derived class "contains" everything that an instance of the
base class would have contained, plus everything that the
derived class added. So, there is a sort of "sub-object" representing the
base class
within the object of the derived class. Also, the base class' constructor is invoked (before the
derived class' constructor) when an object of the
derived class is created. But there are
no two separate objects!
Consider the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
class A
{
public:
A(const uint64_t a, const uint64_t b, const uint64_t c)
{
this->a = a;
this->b = b;
this->c = c;
}
private:
uint64_t a, b, c;
};
class B : public A
{
public:
B(const uint64_t a, const uint64_t b, const uint64_t c, const uint64_t x, const uint64_t y, const uint64_t z)
:
A(a, b, c)
{
this->x = x;
this->y = y;
this->z = z;
}
private:
uint64_t x, y, z;
};
int main()
{
A* ptr_a = new A(1, 2, 3);
printf("size of A = %zu\n", _msize(ptr_a));
B* ptr_b = new B(1, 2, 3, 4, 5, 6);
printf("size of A = %zu\n", _msize(ptr_b));
}
|
Output:
size of A = 24
size of B = 48 |
We can see that an object of the
derived class B has
twice the size of an object of the
base class A. That is because an object of class B needs to contain the three fields inherited from class A (which are 8 bytes in size each, so 24 bytes overall)
plus the three additional fields added by class B (again 24 bytes).
If, there really were two separate objects in memory, and the B-object contained an implicit pointer to a "hidden" A-object, then this would look different! A pointer is only 4 or 8 bytes in size, so the B-object would then be 28 or 32 bytes in size, but certainly
not 48 bytes. Also, how exactly would the memory block for the "hidden" A-object be allocated, and how could we ever free that memory to avoid memory leaks?
Long story short, in reality there are
no two separate objects in memory, only
one "combined" object.