简体   繁体   English

默认构造函数是否需要调用基类的默认构造函数?

[英]Do default constructors need to call base class default constructors?

Was reading this answer and it surprised me, the suggestion you must always call a base class constructor in the derived class constructor. 在读这个答案时 ,我很惊讶,建议您必须始终在派生类构造函数中调用基类构造函数。 What if you are working only with default constructors, consider: 如果仅使用默认构造函数,该怎么办,请考虑:

class Bar : public Foo {
private:
int y;

public:
Bar() : Foo(), y(0) {
}

...

Is the call to Foo() really necessary here? 在这里真的需要调用Foo()吗?

You do not need to explicitly call a base class constructor in your constructor, in which case the compiler implicitly calls the default constructor, or you get a compile-time error, if none is callable. 您无需在构造函数中显式调用基类构造函数,在这种情况下,编译器将隐式调用默认构造函数,否则,如果没有可调用的编译器,则会出现编译时错误。
Same applies to members who are non-POD. 非POD成员也是如此。

An alternative is a member initialiser list only consisting of a delegation to another constructor of your class, thus creating a delegating constructor. 另一种方法是成员初始化程序列表,该列表包含对类的另一个构造函数的委派,从而创建一个委托构造函数。

No, you don't. 不,你没有。 The reason why this is done is readability. 这样做的原因是可读性。 It's clearer to read and might hint some IDEs helper logic like where the Baseclass::Baseclass() method is used. 阅读起来更清晰,并且可能会提示一些IDE帮助程序逻辑,例如使用Baseclass :: Baseclass()方法的位置。

您不需要调用它们,但就可读性而言,我认为这是一个好主意,并且还可以向审阅代码的人员证明您理解该类是派生的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM