Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialize a const variable of a base class in a derived class' constructor in C++?

I have an abstract C++ class with no constructor. It's supposed to be a base class so other classes can inherit from it. What I am trying to do is to declare a constant variable in the base class and initialize it in each derived class' constructor but nowhere else in each one of those classes. Is it legal in C++? If so, how can I do that?

like image 216
user246392 Avatar asked Oct 11 '10 08:10

user246392


People also ask

How do you initialize a base class from a derived class?

When we inherit class into another class then object of base class is initialized first. If a class do not have any constructor then default constructor will be called. But if we have created any parameterized constructor then we have to initialize base class constructor from derived class.

How do you initialize a const member variable in a class?

To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.

How do you call a base class constructor from a derived class constructor in C++?

Whenever the derived class's default constructor is called, the base class's default constructor is called automatically. To call the parameterized constructor of base class inside the parameterized constructor of sub class, we have to mention it explicitly.

How do you initialize a constant variable?

Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero. A program that demonstrates the declaration of constant variables in C using const keyword is given as follows.


1 Answers

Is it legal in C++?

No. The constant must be initialized in the base class constructor.

The solution is to provide an appropriate constructor in your base class – otherwise it cannot be used. Furthermore, there’s no reason not to provide that constructor.

class Base {
    int const constant;
public:
    virtual ~Base() = 0; // Makes this an abstract base class.
protected:
    Base(int c) : constant(c) { }
};

// Must be implemented!
Base::~Base() { }

class Derived : public Base {
public:
    Derived() : Base(42) { }
};
like image 84
Konrad Rudolph Avatar answered Oct 19 '22 11:10

Konrad Rudolph