Can anyone please tell me why the base class's constructor method is called twice?
#include <iostream>
using namespace std;
class A{
public:
A(){
cout << "default constructor of base class" << endl;
}
};
class B:public A{
public:
B(){
A();
cout << "default constructor of derived class" << endl;
}
};
int main(int argc, char **argv){
B b;
return 0;
}
And I'm getting this unexpected result:
default constructor of base class
default constructor of base class
default constructor of derived class
Once constructing the base sub-object of the B
object in main
:
B b;
Once constructing the temporary A
object in the constructor of B
:
A();
Perhaps you meant to initialise the A
sub-object; do that in the initialiser list, not the constructor body:
B() : A() {
cout << "default constructor of derived class" << endl;
}
although, in this case, that would do exactly the same thing as leaving it out altogether.