I have a template class "Derived" which does a constructor inheritance:
template <class T>
class Derived : public T
{
using T::T;
Derived()
{
std::cout<<"in derived";
}
};
My base class has a constructor that expects arguments:
class Base
{
public:
Base(int a)
{
std::cout<<"in base";
}
};
When I create an object of type Derived it seems the derived constructor is not called:
Derived<Base> derived(2);
prints "in base";
Why? Is there a way to tell it to call Derived constructor?
Initialization by an inherited constructor happens as follows:
[class.inhctor.init] (emphasis mine)
1 When a constructor for type B is invoked to initialize an object of a different type D (that is, when the constructor was inherited), initialization proceeds as if a defaulted default constructor were used to initialize the D object and each base class subobject from which the constructor was inherited, except that the B subobject is initialized by the invocation of the inherited constructor. The complete initialization is considered to be a single function call; in particular, the initialization of the inherited constructor's parameters is sequenced before the initialization of any part of the D object.
The key point is the defaulted word. Defaulted c'tors are generated by the compiler, for instance a copy c'tor can be defaulted. And so it doesn't use any c'tor that's defined in the derived class. A compiler generated c'tor is always going to have an empty compound statement. So one should not expect anything to be printed.
Related
Say I have a base and derived class like this:
class Base {
public:
Base() { ... };
Base(int param) { ... };
};
class Derived : public Base {
public:
Derived() { ... };
Derived(int param) { ... };
Derived(int p1, int p2) { ... };
};
Note that I'm not explicitly calling any of Base's constructors for Derived's constructors. That is to say, I didn't write Derived() : Base() { ... } or Derived(int param) : Base(param) { ... }.
Do any of Base's constructors get called by default when creating an instance of Derived?
If so, does Base(int param) get called when using Derived(int param), or does Base() get called?
Put another way, does C++ always default to using a base class's constructor with the same signature as the derived class's constructor if you don't specify which constructor to use? Or does it just use the base class's default constructor?
If the former, what about when using a constructor in the derived class that doesn't have a matching constructor with the same signature in the base class, such as Derived(int p1, int p2)?
Please note this question does not relate to initialization of member variables of either class. I intentionally did not include any member variables in my pseudo-code. It specifically has to do with which constructor on the base class gets used if you do not explicitly specify a base constructor in the derived class's constructors.
Quoting from cppreference's description of constructors and how inheritance relates to them:
Before the compound statement that forms the function body of the constructor begins executing, initialization of all direct bases, virtual bases, and non-static data members is finished. Member initializer list is the place where non-default initialization of these objects can be specified. For bases and non-static data members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified. No initialization is performed for anonymous unions or variant members that do not have a member initializer.
(Emphasis added.)
If you do not specify an initialization of the base class subobject in your derived class's constructor's member initializer list, the base class subobject is default-initialized.
Consider following code:
class TBase {
public:
TBase();
TBase(const TBase &);
};
class TDerived: public TBase {
public:
using TBase::TBase;
};
void f() {
TBase Base;
TDerived Derived(Base); // <=== ERROR
}
so, I have base and derived classes, and want to use "using TBase::TBase" to pull copy ctor from base class to be able to create instance of derived class in such way:
TDerived Derived(Base);
But all compilers rejects this with these error messages
7 : note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'TBase' to 'const TDerived' for 1st argument
Why? What am I doing wrong? Why "using TBase::TBase" does not work in this situation?
UPDATE
How can be explained following piece of code from cppreference.com?
struct B1 {
B1(int);
};
struct D1 : B1 {
using B1::B1;
// The set of inherited constructors is
// 1. B1(const B1&)
// 2. B1(B1&&)
// 3. B1(int)
Copy and move consturctors (and the default constructor) are never inherited, simply because the standard says so. All other constructors are.
That comment on cppreference was misleading(1). The same comment in the standard says:
The candidate set of inherited constructors in D1 for B1 is
(Emphasis mine).
The standard then goes on to say that only the D1(int) constructor is actually inherited. The copy and move constructors for D1 are implicitly-declared as for any other class, not inherited.
Refer to C++14 12.9 [class.inhctor] for details.
(1) I submitted a change to cppreference to hopefully clarify this.
If you further read the same piece of code, it says:
// D1 has the following constructors:
// 1. D1()
// 2. D1(const D1&)
// 3. D1(D1&&)
// 4. D1(int) <- inherited
};
Thus a copy ctor is still the copy ctor, it accepts an argument of class TDerived. D1(int) is generated automatically nevertheless.
As per standard 12.6.3/p1 Initialization by inherited constructor [class.inhctor.init] (Emphasis Mine):
When a constructor for type B is invoked to initialize an object of a
different type D (that is, when the constructor was inherited
(7.3.3)), initialization proceeds as if a defaulted default
constructor were used to initialize the D object and each base class
subobject from which the constructor was inherited, except that the B
subobject is initialized by the invocation of the inherited
constructor. The complete initialization is considered to be a single
function call; in particular, the initialization of the inherited
constructor’s parameters is sequenced before the initialization of any
part of the D object.
Thus, constructors are not actually inherited but rather they're implicitly or explicitly called by the respective derived constructor. Also keep in mind that the inherited constructors are simply calling the base constructors and do not perform any member initialization in the derived object.
To clarify this consider the following example:
struct Base {
Base(int);
...
};
struct Derived : Base {
using Base::Base;
...
};
The above Derived class definition is syntactically equivalent with:
struct Derived : Base {
Derived(int i) : Base(i) {}
...
};
That is, the using declaration in the Derived class implicitly defines the constructor Derived(int). At this point mind also that if the constructor is inherited from multiple base class sub-objects Derived, the program is ill-formed.
In the same manner you've been lead to the logical conclusion that since I've declared in the base class a copy constructor with the using declaration:
class TBase {
public:
TBase();
TBase(const TBase &);
};
class TDerived: public TBase {
public:
using TBase::TBase;
};
I would get the following syntactical equivalent Derived class:
class TDerived: public TBase {
public:
TDerived() : Base() {}
TDerived(TBase const &other) : Base(other) {}
};
However, this is not the case. You can't "inherit" a copy constructor neither a default constructor neither a move constructor. Why? because this is how the C++ standard dictates so.
What you can do instead is to define a user defined constructor that will take as input a base class object:
class TDerived: public TBase {
public:
TDerived(TBase const &other) {}
};
After all TDerived and TBase are different classes even though the first inherits the second one.
One of the requirements of constructor inheritance is that the derived class can not have any constructors with the same signature. I am unsure however about how deleted functions behave under these rules.
class Foo
{
public:
Foo() = delete;
Foo(const Foo& a_Foo) = delete;
Foo(int a_Value) : m_Value(a_Value) {}
private:
int m_Value;
};
class Bar : public Foo
{
public:
using Foo::Foo;
Bar() : Foo(7) {};
Bar(const Bar& a_Bar) : Foo(12) {};
};
Are deleted constructors inherited at all?
If so, Bar() and Foo() have the same signature, does this make the code invalid?
You could argue that Foo(const Foo& a_Foo) and Bar(const Bar& a_Bar) have different signatures. How do copy constructors behave under constructor inheritance?
Default, copy, and move constructors are not inherited, nor can inheriting a constructor implicitly declare a copy or move constructor for the derived class. Also, an inheriting constructor declaration will essentially just "skip over" a base class constructor if there's already a constructor with the same signature in the derived class.
For each non-template constructor in the candidate set of inherited constructors other than a constructor
having no parameters or a copy/move constructor having a single parameter, a constructor is implicitly
declared with the same constructor characteristics unless there is a user-declared constructor with the same
signature in the complete class where the using-declaration appears or the constructor would be a default,
copy, or move constructor for that class.
([class.inhctor]/3)
Also, an inherited constructor is deleted if the corresponding base class constructor is deleted.
A constructor so declared has the same access as the corresponding constructor in X. It is deleted if the
corresponding constructor in X is deleted (8.4). An inheriting constructor shall not be explicitly instantiated (14.7.2) or explicitly specialized (14.7.3).
([class.inhctor]/4)
Foo constructor is deleted, so you can't define a constructor of class Bar that uses deleted Foo constructor. It doesn't make sense to talk about inheritance there, because you can never create an object of class Bar that uses deleted Foo constructor.
Are deleted constructors inherited at all?
No. They are deleted, there is nothing to inherit from.
If so, Bar() and Foo() have the same signature, does this make the
code invalid?
Default constructor can't be inherited.
You could argue that Foo(const Foo& a_Foo) and Bar(const Bar& a_Bar)
have different signatures. How do copy constructors behave under
constructor inheritance?
Copy constructors can't be inherited as well.
Consider the following example:
class Symbol {
public:
Symbol() = delete;
Symbol(char ch) : c{ch} {}
private:
char c;
//
};
class Derived : Symbol {
public:
private:
int i;
};
class NotDerived {
public:
private:
int i;
};
The following line would not compile. You cannot create an object of a class with a deleted constructor. Everyone knows that.
// Can't create an object because of deleted constructor.
Symbol sym;
However, you can create the object of the base class using the overloaded constructor:
// Parametrized constructor, this one is fine.
Symbol sym_char('a');
The Derived class, using : public inheritance, inherits everything from the base Symbol class, including the deleted constructor. Indeed, if the Symbol class has a deleted constructor, disallowing you to create objects of that class using the default constructor, then logically the Derived class should also forbid you to create objects of that class using the deleted constructor.
// note: default constructor of 'Derived' is implicitly deleted because base class 'Symbol' has a deleted default constructor
// The deleted consturctor is inherited from the base class.
Derived d;
The Derived class inherits all and any methods from the Symbol class, including any deleted constructors!
If you take away the inheritance statement, observe that the inherited deleted constructor disappears. There is no deleted constructor any more. Now the default compiler generated default constructor comes back, because the deleted constructor isn't overwriting it.
// No deleted constructor: works
NotDerived nd;
The NotDerived class has a compiler generated default constructor, because it is not inheriting from anything. The Derived class does not have a default constructor, it has a deleted constructor, because it inherits from a class that has a deleted constructor.
So as we see in the above experiments, yes all and any methods that are in the base class including deleted ones get inherited into the derived class. This means that yes deleted constructors in base classes do get inherited into derived classes!
$8.5/7 states that
— if T is a (possibly cv-qualified) non-union class type without a user-provided constructor, then the object
is zero-initialized and, if T’s implicitly-declared default constructor is non-trivial, that constructor is
called.
I am unable to appreciate the last part of this statement "if T’s implicitly-declared default constructor is non-trivial, that constructor is called."
Can someone please explain this with an example?
class A
{
int x;
};
class B : A {};
B b{};
I think B in the code above is having a non-trivial constructor. But how do I observe call to B's implicitly declared constructor and make sure that my compiler is calling it?
I think B in the code above is having a non-trivial constructor.
In your example, the constructor is trivial.
Looking at the conditions in C++11 12.1/5, neither class has a user-declared constructor, virtual functions, virtual base classes, members with initialisers, or members of class type; A has no base classes and B only has a trivial base class.
But how do I observe call to B's implicitly declared constructor and make sure that my compiler is calling it?
One way to make a class with an implicit, but non-trivial, default constructor is to have a non-trivial member or base class:
struct A {
// A user-declared constructor is non-trivial
A() {std::cout << "Construct A\n";}
};
struct B : A {};
Now you can (indirectly) observe the implicit constructor of B being called, by observing the side-effect when it calls the constructor of A.
Explanation after N3797:
A function is user-provided if it is user-declared and not explicitly
defaulted or deleted on its first declaration.
Therefore, since you don't declare a default constructor for B, it is not user-provided.
The following then applies:
A default constructor is trivial if it is not user-provided and if:
— its class has no virtual functions (10.3) and no virtual base
classes (10.1), and
— no non-static data member of its class has a
brace-or-equal-initializer, and
— all the direct base classes of its class have trivial default
constructors, and
— for all the non-static data members of its class that are of class
type (or array thereof), each such class has a trivial default
constructor.
So it is indeed trivial, since we can apply the same procedure recursively for A.
Other examples:
struct A { A() = default; }; // Trivial default constructor!
struct A { A() = delete; }; // Also trivial!
struct A { A(); }; // Can't be trivial!
struct B { virtual void f(); }
struct A : B {}; // Non-trivial default constructor.
struct B {};
struct A : virtual B {}; // Non-trivial default constructor.
Imagine you have this one
struct A {
string a;
int value;
};
int main() {
A a = A();
return a.value;
}
a.value is zero when we return that value, because the object was zero-initialized. But that is not enough, because a also contains a string member which has a constructor. For that constructor to be called, the standard arranges that A's constructor is called, which will eventually lead to constructing the member.
basic c++ question i'm fairly sure. if i have a base class with a constructor that takes no parameters, and just initializes some of the protected members, does a derived class instantly call this base constructor too if it matches the parameters (wishful but unlikely thinking), and if not, is there a way to force it to automatically call said base constructor from the derived class WITHOUT having to explicitly tell it to do so in the derived class? I ask because i'm writing a wrapper of sorts and there are some protected members that i want initialized to specific values initially, and then i want to derive and manipulate this base class to my needs, but i wouldn't like an outside user to have to remember to explicitly call the base constructor or set these values within their own constructor.
Yes, the default base constructor is always called unless explicitly stated otherwise.
For example:
class A
{
public:
A() { std::cout << "A"; }
};
class B : A
{
public:
B() {}
};
int main()
{
B b;
return 0;
}
will output:
A
By "explicitly stated otherwise" I mean that you can call a different constructor from the derived class:
class A
{
public:
A() { std::cout << "A"; }
A(int) { std::cout << "AAA"; }
};
class B : A
{
public:
B() : A(1) {} //call A(int)
};
int main()
{
B b;
return 0;
}
will output
AAA
Important if you don't have a default constructor (you declare a non-default constructor and not a default one) or the default constructor is not visible (marked as private), you need to explicitly call an available constructor in the derived class.
If your base-class has a "default constructor" (a constructor that takes no parameters; either explicitly provided by you, or implicitly provided by the compiler because you didn't explicitly provide any constructors), then every derived-class constructor will automatically call that unless you specify that they call a different constructor instead.
(If your base-class doesn't have a "default constructor", because you've provided one or more constructors that take parameters and no constructor that doesn't, then it's a compile-error for a derived-class constructor not to indicate the base-class constructor it calls.)