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

后端 未结 3 1318
迷失自我
迷失自我 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) { }
    };
    

提交回复
热议问题