开发者

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 tr开发者_JAVA百科ying 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?


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) { }
};


If at all you need to do it this way:

struct Base {
    Base( std::string const & someValue )
    : const_value( someValue ) {
    }
protected:
   std::string const const_value;
};

struct Derived : Base {
    Derived()
    : Base("Derived"){
    }
};

The reason for this is that you are only allowed to assign values to a const value at initialization time. Once Base is initialized you are no longer allowed to modify the value. Therefore you have to do it that way as shown above.


Why don't you make a protected constructor in the abstract base class and set the constant value there?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜