如果抽象基类是一个接口,是否必须在派生类构造函数中调用基类构造函数?
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();
};
派生类构造函数中是否需要调用基构造函数?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,事实上,基类没有必要有一个显式定义的构造函数(尽管要确保有一个虚拟析构函数)。
因此,对于典型的界面,您可以有这样的东西:
编辑:这是您应该有一个虚拟析构函数的原因:
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:
EDIT: Here's a reason why you should have a virtual destructor:
显式调用基类构造函数是从不的义务,除非它有参数。 编译器会自动调用构造函数。 理论上,基类仍然有一个构造函数,但如果它不执行任何操作,编译器可能会将其优化为不存在。
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.
不,不在您提供的示例中。 在初始化派生类的任何成员之前,将按照声明基类的顺序自动调用基类的默认构造函数。
No, not in the example you provided. The base class' default constructors will be called automatically in the same order that the base classes are declared, before any member of the derived class is initialized.
如果基类的构造函数不需要任何参数,则不需要在派生类中调用它,因为它被作为默认构造函数调用。 但是,您需要为基类提供一个虚拟析构函数,即使它是空的。 否则编译器将生成一个默认析构函数,默认情况下该析构函数是非虚拟的。
If the base class's constructor does not need any parameters, you do not need to call it in the derived class since it is called as a default constructor. However you need to provide a virtual destructor for your base class even if it is empty. Otherwise compiler will generate a default destructor which is non-virtual by default.