Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 956
chester89 Avatar asked Dec 10 '22 22:12

chester89


2 Answers

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
like image 91
Evan Teran Avatar answered Mar 09 '23 01:03

Evan Teran


It is never obligatory to explicitly call the base class constructor, unless it has parameters. The compiler will call the constructor automatically. Theoretically the base class still has a constructor, but the compiler may optimize it away into non-existence if it doesn't do anything.

like image 23
Qwertie Avatar answered Mar 09 '23 01:03

Qwertie