Force a Derived Class to use the Constructor of the Base Class

后端 未结 2 508
半阙折子戏
半阙折子戏 2021-01-19 07:55

Is there a way to force a derived class to use the constructor of the abstract base class? It must not be a real constructor, I have an open mind about creative solutions.

2条回答
  •  悲&欢浪女
    2021-01-19 08:05

    As suggested by other users, you must call the base class constructor into the initializer list of derived class constructor.

    But there's another cool solution bringed up by C++11: the inherited constructors:

    class Base
    {
        Base(int Member, string Text) { };
    };
    
    class Derived : public Base
    {
        using Base::Base; // <-- Brings to derived the Base's constructor.
    };
    

    But you must assure that your compiler can use C++11 features; and of course, study if the inherited constructor conforms to your requirements instead of using it just because it's cool.

提交回复
热议问题