Do default constructors need to call base class default constructors?

好久不见. 提交于 2019-12-13 05:17:58

问题


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?


回答1:


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.

An alternative is a member initialiser list only consisting of a delegation to another constructor of your class, thus creating a delegating constructor.




回答2:


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.




回答3:


You do not need to call them but I think it is a good idea in terms of readabilitty and also proves to the person reviewing the code that you understand that the class is derived.



来源:https://stackoverflow.com/questions/22951260/do-default-constructors-need-to-call-base-class-default-constructors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!