简体   繁体   中英

How does a constructor choose a base class constructor in C++

如果您在派生类的构造函数内部,并且没有对基类构造函数进行显式调用,则编译器如何知道要使用哪个基本构造函数?

If a base class is not mentioned in the constructor initializer list , it will be default initialized . Since the base class will definitely be of class type, that means that the default constructor will be called.

Two of those references also have examples of derived classes which implicitly call the base class default constructor. For instance:

struct Class : public Base
{
    unsigned char x;
    unsigned char y;

    Class ( int x )
      : Base ( 123 ), // initialize base class
        x ( x ),      // x (member) is initialized with x (parameter)
        y { 0 }       // y initialized to 0
    {}                // empty compound statement

    Class ( double a )
      : y ( a+1 ),
        x ( y ) // x will be initialized before y, its value here is indeterminate
    {} // base class constructor does not appear in the list, it is
       // default-initialized (not the same as if Base() were used, which is value-init)

   ...
};

It uses the default constructor, as mandated by the standard in N4140 Initializing bases and members , §12.6.2 [class.base.init]/8 (emphasis mine):

In a non-delegating constructor, if a given potentially constructed subobject is not designated by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer ), then

  • if the entity is a non-static data member that has a brace-or-equal-initializer and either

    • the constructor's class is a union, and no other variant member of that union is designated by a mem-initializer-id or
    • the constructor's class is not a union, and, if the entity is a member of an anonymous union, no other member of that union is designated by a mem-initializer-id ,

    the entity is initialized as specified in 8.5;

  • otherwise, if the entity is an anonymous union or a variant member, no initialization is performed;

  • otherwise, the entity is default-initialized .

Note that base classes are potentially constructed subobjects per Special member functions , §12 [special]/5:

For a class, its non-static data members, its non-virtual direct base classes, and, if the class is not abstract, its virtual base classes are called its potentially constructed subobjects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM