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

后端 未结 3 1313
迷失自我
迷失自我 2020-12-16 13:04

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 var

3条回答
  •  抹茶落季
    2020-12-16 13:39

    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.

提交回复
热议问题