0

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?

samjarvis
  • 13
  • 3
  • 1
    You've mixed up "initializer lists" with "base class initializers" and "member initializers". The code in that link would work fine in C++98. – Sneftel Jun 10 '21 at 17:44
  • 2
    (Incidentally, that web page is awful. Please see https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list for better options.) – Sneftel Jun 10 '21 at 17:45

2 Answers2

1

The syntax to delegate to the base class constructor from the derived class constructor would be as follows

class InitilizerList_ : public Base_
{
public:
    // default constructor
    InitilizerList_() : Base_(10)
    {
        cout << "InitilizerList_'s Constructor" << endl;
    }
};
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

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;
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402