class A {
A() { }
};
class B : public A {
B() : A() { }
};
Why do we need to call the base class's constructor explicitly inside B's constructor? Isn't it implicit?
class A {
A() { }
};
class B : public A {
B() : A() { }
};
Why do we need to call the base class's constructor explicitly inside 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 only needed in case A's constructor requires extra parameters. In your example, it is not necessary to call the base class' constructor explicitly.
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.
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.