I have this sample code:
#include <iostream>
class A
{
public:
A()
{
std::cout << "Default constructor of A" << '\n';
}
A(int i)
{
std::cout << "Inside the constructor of A with one int argument" << '\n';
}
};
class B : A
{
using A::A;
public:
B()
{
std::cout << "Default constructor of B" << '\n';
}
};
int main()
{
B b(12);
std::cout << "End of main";
}
Which outputs:
Inside the constructor of A with one int argument
End of main
My expectation would be for the output to be like this:
Inside the constructor of A with one int argument
Default constructor of B
End of main
I'm basing this on cppreference which claims: "If overload resolution selects one of the inherited constructors when initializing an object of such derived class, then the Base subobject from which the constructor was inherited is initialized using the inherited constructor, and all other bases and members of Derived are initialized as if by the defaulted default constructor (default member initializers are used if provided, otherwise default initialization takes place). The entire initialization is treated as a single function call: initialization of the parameters of the inherited constructor is sequenced-before initialization of any base or member of the derived object."
Am I misreading this somehow? Is the default derived constructor not meant to be called after an inherited constructor?
The quote says:
[...] are initialized as if by the defaulted default constructor [...]
A defaulted default constructor would be
struct foo {
foo() = default;
// defaulted because = default;
// default constrcutor because can be called without arguments
};
And the quote explains that members, bases subobjects etc. are initializes "as if" by such a defaulted default constructor. The quote does not say anywhere that a default constructor is actually called. Moreover, your constructor is not a defaulted default constructor. Its a default constructor, but with a custom implementation, ie its not defaulted.
PS: To get the output you expect one does not need inheriting constructors (which is a feature that was only added in C++11), but you would write:
class B : A
{
public:
B(int x) : A(x)
{
std::cout << "Default constructor of B" << '\n';
}
};