Logo

Blog


Using base class constructor

While preparing slides for my next on-site training I stumbled across the C++11 powers of using. Specifically together with constructors of a base class. Here is a sample:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Foo
{
public:
    Foo(double amount) {}
    Foo(int x, int y = 2) {}
};

class Bar : public Foo
{
public:
    using Foo::Foo;

    int mX;
};

int main()
{
    Bar bar0{100.0};
    Bar bar1(100.0);

    Bar bar2(1);
}

This is another neat feature to reduce repetition in our code. Except with one downside, these constructors do not initialize members of the derived class. You probably already know that. However, this was the point I like to show to the attendees with C++ Insights. It turned out that C++ Insights did not support this transformation. It does now:

C++ Insights shows the transformation of using with base constructors.

In this transformation you can see what happens behind your back. The compiler introduces a constructor, or constructors, with the same parameters as in the base class. This constructor calls it correspondent in the base class. Finished. The member variables of the derived class do not get initialized. To prevent this missing initialization C++11 also gave us in class initialization of variables:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Foo
{
public:
    Foo(double amount) {}
    Foo(int x, int y = 2) {}
};

class Bar : public Foo
{
public:
    using Foo::Foo;
    int mX{1};
};

int main()
{
    Bar bar0{100.0};
    Bar bar1(100.0);

    Bar bar2(1);
}

If you change your code such that you inline-initialize mX the generated code changes as you can see in this output.

Have fun with C++ Insights. You can support the project by becoming a Patreaon or of course with code contributions.

Andreas