开发者

What is the importance of invoking base class constructor explicitly?

class A {
    A() { }
};

class B : public A {
    B() : A() { }
};

Why do we need to call the base class's constructor explicitly insi开发者_StackOverflow中文版de B's constructor? Isn't it implicit?


It is implicit. You'll need this syntax in case A has a constructor that has arguments, this is the way to pass them.


This is implicit and unnecessary. If you do not call the base class constructor explicitly, the default constructor (the one with no parameters) is used.

There is only a need to call a constructor explicitly if the base class does not have a default constructor, or if you want to call a different one than the default constructor.

The explicit call to the base class constructor can still be added for clarity, but it is not required.


This is only needed in case A's constructor requires extra parameters. In your example, it is not necessary to call the base class' constructor explicitly.


In the case you've shown, it's not necessary. Consider the following:

class A 
{
private:
    int m_i;

public:
    A(int i) 
      : m_i(i)
    { 
    } 
}; 
class B:public A 
{ 
public:
    B()
    { 
    } 
};

This won't work (will not compile) because there is no longer a default constructor for A. In this case, you have to explicitly call the base class constructor with the appropriate argument.

The other time you may have to explicitly call a constructor is when the base class has multiple constructors. In this case, you can explicitly call the one that makes sense.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜