Search code examples
c++c++11inheritancedecoratorc++98

c++ Inheritance (no base constructor) without initializer lists (lower than c++ 11)?


I am implementing the Decorator design pattern in c++ and I ran into this problem (code taken from https://www.studytonight.com/cpp/initializer-list-in-cpp.php):

#include<iostream>
using namespace std;

class Base_
{
    public:
    // parameterized constructor
    Base_(int x)
    {
        cout << "Base Class Constructor. Value is: " << x << endl;
    }
};

class InitilizerList_:public Base_
{
    public:
    // default constructor
    InitilizerList_()
    {
        Base_ b(10);
        cout << "InitilizerList_'s Constructor" << endl;
    }
};

int main()
{
    InitilizerList_ il;
    return 0;
}

As the website states, this doesn't compile because the base constructor gets called before the derived constructor, and this problem is solved using initializer lists. My question is: Can this be implemented without initializer lists and if so, how? Initializer lists were introduced in c++ 11 (I think) so what if you were trying to do this in c++ 98 for example?


Solution

  • You're getting confused on the terminology. There is an initializer list, which looks like { for, bar, baz, ... }, there is a std::initializer_list type that can wrap an initilizer list, and then there is the class member initialization list, which is used to initialize the members in the class.

    That last one is what you want and has been part of C++ since it was created. Using one would give you

    InitilizerList_() : Base_(10)
    {
        cout << "InitilizerList_'s Constructor" << endl;
    }