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

后端 未结 3 1312
迷失自我
迷失自我 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:33

    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) { }
    };
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-16 13:39

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

    0 讨论(0)
提交回复
热议问题