Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I call the base class default constructor in the initialization list?

class A : public B
{
  ...
}

// case I : explicitly call the base class default constructor
A::A() : B()
{
  ...
}

// case II : don't call the base class default constructor
A::A() // : B()
{
  ...
}

Is the case II equal to case I?

To me, I assume that the default constructor of base class B is NOT called in case II. However, despite still holding this assumption, I have run a test which proves otherwise:

class B
{
public:
    B()
    {
        cout << "B constructor" << endl;
    }
};

class A : public B
{
public:
    A()
    {
        cout << "A constructor" << endl;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    A a;
    return 0;
}

// output from VS2008

B constructor
A constructor
Press any key to continue . . .
like image 841
q0987 Avatar asked Apr 25 '11 15:04

q0987


People also ask

Does initializer list call constructor?

An initialization list can be used to explicitly call a constructor that takes arguments for a data member that is an object of another class (see the employee constructor example above). In a derived class constructor, an initialization list can be used to explicitly call a base class constructor that takes arguments.

Which is the correct way to call the base class constructor?

For multiple inheritance order of constructor call is, the base class's constructors are called in the order of inheritance and then the derived class's constructor.

Does a base class need a default constructor?

If a base class does not offer a default constructor, the derived class must make an explicit call to a base constructor by using base.

Which constructor will initialize the base class?

The data members j and k , as well as the base class A must be initialized in the initializer list of the constructor of B . You can use data members when initializing members of a class.


2 Answers

The base class constructor is called in both cases.

Here is a link to an article with more info.

like image 195
rerun Avatar answered Oct 17 '22 02:10

rerun


If the base class constructor doesn't take any argument, then explicit mention of it in the initialization list is not needed.

like image 40
Nawaz Avatar answered Oct 17 '22 03:10

Nawaz