tags:

views:

140

answers:

4
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?

+11  A: 

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

Drakosha
Cool trick: Sometimes I don't want the parent's constructor to be called (maybe there's some info the class can't function without), so I make it private. When I do that I have to call the proper parent constructor explicitly every time, even in the child's default constructor.
thebretness
+3  A: 

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.

Dimitri C.
+7  A: 

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.

Thomas
A: 

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.

Matt Davis
nitpick: remove the `:` in `B():` :)
Matthieu M.