Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a default constructor to a base class changes sizeof() a derived type [duplicate]

I tend to think I have a pretty good grasp of C++ internals and memory layouts, but this one has me baffled. I have the following test code:

#include <stdio.h>

struct Foo
{
    //Foo() {}
    int x;
    char y;
};

struct Bar : public Foo
{
    char z[3];
};

int main()
{
    printf( "Foo: %u Bar: %u\n", (unsigned)sizeof( Foo ), (unsigned)sizeof( Bar ) );
}

The output is reasonable:

Foo: 8 Bar: 12

However, this is the very odd part, if I uncomment that simple default constructor on Foo(), the sizeof( Bar ) changes! How can the addition of a ctor possibly change the memory layout of these classes?

Foo: 8 Bar: 8

Compiled using gcc-7.2

like image 290
ByteMe95 Avatar asked Dec 20 '17 21:12

ByteMe95


People also ask

Does a derived class inherits a base class constructor by default?

In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class.

Can a constructor be derived from base class?

To call the parameterized constructor of base class when derived class's parameterized constructor is called, you have to explicitly specify the base class's parameterized constructor in derived class as shown in below program: C++

Can a derived class have a constructor with default parameters?

A derived class cannot have a constructor with default parameters.

Does default constructor call base constructor?

By default, a derived class when instantiated will always IMPLICITLY call the base class default constructor. That is why in most cases, you do NOT need to add "base()" to a derived class's constructor.


1 Answers

GCC follows the Itanium ABI for C++, which prevents the tail-padding of a POD being used for storage of derived class data members.

Adding a user-provided constructor means that Foo is no longer POD, so that restriction does not apply to Bar.

See this question for more detail on the ABI.

like image 172
M.M Avatar answered Oct 21 '22 13:10

M.M