Search code examples
c++oopconstructorclass-designabstract-class

If abstract base class is an interface, is it obligatory to call base class constructor in derived class constructor?


class AbstractQuery {
    virtual bool isCanBeExecuted()=0;
public:
    AbstractQuery() {}
    virtual bool Execute()=0;
};

class DropTableQuery: public AbstractQuery {
    vector< std::pair< string, string> > QueryContent;
    QueryValidate qv;
public:
    explicit DropTableQuery(const string& qr): AbstractQuery(), qv(qr) {}
    bool Execute();
};

Is it necessary to call base contructor in derived class constructor?


Solution

  • No, in fact for it is unnecessary for the base class to have an explicitly defined constructor (though make sure you have a virtual destructor).

    So for a typical interface you could have something like this:

    class MyInterface {
    public:
        virtual ~MyInterface() {}
        virtual void execute() = 0;
    };
    

    EDIT: Here's a reason why you should have a virtual destructor:

    MyInterface* iface = GetMeSomeThingThatSupportsInterface();
    delete iface; // this is undefined behaviour if MyInterface doesn't have a virtual destructor