Search code examples
c++constructorc++14language-lawyerctor-initializer

Constructor with an empty mem-initializer-list and an empty body


Where can I find in the Standard (C++14) a clause stating that an user-defined default constructor with an empty mem-initializer-list and an empty body invokes the default constructor for each base class and for each member sub-object. For instance consider the code below:

#include <iostream>
class A{
public:
    A() {std::cout << "A" << '\n'; }
};

class Base{
public:
    Base() { std::cout << "Base" << '\n'; }
};

class Derived : public Base {
    A a;
public:
    Derived() {}
};

int main()
{
    Derived d;
}

The constructors for both Base and A are called by the user-declared constructor Derived() with an empty mem-initializer-list and an empty body.


Solution

  • Quoting from the draft standard N4527 12.6.2/9 Initializing bases and members [class.base.init] (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

    (9.1) — if the entity is a non-static data member that has a brace-or-equal-initializer and either

    (9.1.1) — the constructor’s class is a union (9.5), and no other variant member of that union is designated by a mem-initializer-id or

    (9.1.2) — 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;

    (9.2) — otherwise, if the entity is an anonymous union or a variant member (9.5), no initialization is performed;

    (9.3) — otherwise, the entity is default-initialized (8.5).

    Note: As @Howard Hinnant pointed out in the comments below, in C++14 (N4141) "finalized" standard the above quote lies in paragraph 8 and not paragraph 9.