Initializing values ​​for classes with exclusively inherited constructors

According to cppreference, types of non-union classes without any user-created constructors will be initialized with zeros before building:

If T is a type of non-unit class without any user-supplied constructors, then the object is initialized to zero, and then the implicitly declared default constructor is called (if it is not trivial)

I'm not sure what should happen when C ++ 11 inherited constructors are used, as the quote explicitly mentions the default constructor implicitly declared .

In the following example:

#include <iostream> struct A { int a; A() {} A(int i): a(i) {} }; struct B: public A { using A::A; }; int main() { B b { 5 }; B* p = new (&b) B{ }; std::cout << ba << std::endl; } 

What is the correct conclusion, 0 or 5? If a class type that provides only inherited constructors is initialized to zero before initialization is initialized ( B{ } )?

+6
source share
1 answer

The correct answer is 0 , since the default constructor for B implicitly declared.

Note that the default constructors copy and move are not inherited; citing from §12.9 / 3 [class.inhctor]

For each constructor without a template in the candidate set of inherited constructors , except for the constructor without parameters or the copy / move constructor with a single parameter , the constructor is implicitly declared with the same constructor characteristics if there is no constructor declared by the user with the same signature in the full class where it appears the declaration of use or constructor will, by default, copy or move the constructor for this class.


Your example is similar to that in N3797, §12.9 / 6 (edited for brevity)

 struct B2 { B2(int = 13, int = 42); }; struct D2 : B2 { using B2::B2; }; 

The set of candidates for inherited designers in D2 for B2 is
- B2(const B2&)
- B2(B2&&)
- B2(int = 13, int = 42)
- B2(int = 13)
- B2()

The set of constructors present in D2 is
- D2() , an implicitly declared default constructor, not inherited
- D2(const D2&) , an implicitly declared copy constructor, not inheritable
- D2(D2&&) , an implicitly declared move mechanism, not inherited
- D2(int, int) , an implicitly declared inheriting constructor
- D2(int) , an implicitly declared inheriting constructor

In your case, the set of candidates for inherited constructors in B for A is

 A() A(int) A(const& A) A(A&&) 

and the constructors present in B are

 B() implicitly declared, not inherited B(int) implicitly declared, inherited B(const& B) implicitly declared, not inherited B(B&&) implicitly declared, not inherited 
+6
source

Source: https://habr.com/ru/post/958968/


All Articles