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
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.
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++
A derived class cannot have a constructor with default parameters.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With