2
votes

Consider the diamond scenario below:

class Base {
    int x;
public:
    virtual ~Base(){}
};

class Derived1 : virtual public Base {
    int y;
};

class Derived2 : virtual public Base {
    int z;
};

class Derived3 : public Derived1, public Derived2 {
    int t;
};
  • Size of Base is 8 [x(4) + vptr(4) (from virtual destructor)]
  • Size of Derived1 is 16 [x(4) + y(4) + vptr(4) (from virtual destructor) + vptr(4) (from virtual inheritance)]
  • Size of Derived2 is 16 [x(4) + z(4) + vptr(4) (from virtual destructor) + vptr(4) (from virtual inheritance)]
  • Size of Derived3 is 28 [x(4) + y(4) + z(4) + t(4) + vptr(4) (from virtual destructor) + 2 times vptr(4) (from virtual inheritance of Derived1 and Derived2)]

Now, if I add another class Derived4 which derives from Derived 3,

class Derived4 : public Derived3 {
    int s;
};

it's size comes out to be 32 (which I'm assuming to be size of Derived3 + s).

I want to know if there is no virtual pointer inside Derived4?

If I take a normal class hierarchy (without diamond structure), then if a base class has a virtual function, then all derived classes have vptrs. So, why not in this case?

I'm compiling the code in codeBlocks 12.11 with GNU GCC compiler.

1

1 Answers

0
votes

Since Derived4 has not added any virtual functions or virtual base classes, beyond what it has inherited from Derived3, the only increase in size is for the member s.