'If derived classes do not add new members, will instances take up the same memory as the base class?

Consider the sample code below.

  1. Does the standard define if b and d should have the same storage size? Does it define they should not have the same size (due to some needed extra storage)?
  2. If the standard does not specify anything explicitly, do actual compilers typically use the same size for b and d? Does it depend on the contents of the classes? What are possible exceptions? (of compilers, and or specific declarations/definitions)

.

class base {
    // Any possible list of data members (static, inline, etc.) and 
    // methods (virtual, pure virtual, inline, non-virtual, etc.) 
};

class derived : public base {
public:
    // Only new methods (whatever... constructors, overrides, etc.), 
    // no new data members
};

base b;
derived d;


Solution 1:[1]

AFAIK, the standard makes no guarantee at all for the size of class instances.

In common implementations, a class instance has memory for each of its non static data members + a pointer to its class vTable. The vTable is not defined by the standard and is only an implementation detail. It commonly contains the addresses of the virtual methods defined in the class, and a version of all the base classes vTables with the actual implementation of their virtual method. It also contains the Real Time Type Information for the class.

That means that in most common implementations, an intance of a subclass that adds no member to its base class should have the same size as an instance of that base class. But as it is only an undocumented implementation detail, you should not rely on that.

BTW I am even unsure if all common implementation have only one single pointer to a vTable, or different pointers to the class vTable and all the base class ones.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Serge Ballesta