I have the following code [This is an interview question]:
#include <iostream>
#include <vector>
using namespace std;
class A{
public:
A(){
cout << endl << "base default";
}
A(const A& a){
cout << endl << "base copy ctor";
}
A(int) {
cout << endl << "base promotion ctor";
}
};
class B : public A{
public:
B(){
cout << endl << "derived default";
}
B(const B& b){
cout << endl << "derived copy ctor";
}
B(int) {
cout << endl << "derived promotion ctor";
}
};
int main(){
vector<A> cont;
cont.push_back(A(1));
cont.push_back(B(1));
cont.push_back(A(2));
return 0;
}
The output is :
base promotion ctor
base copy ctor
base default
derived promotion ctor
base copy ctor
base copy ctor
base promotion ctor
base copy ctor
base copy ctor
base copy ctor
I am having trouble understanding this output, specifically why base default is called once and the last 3 copy ctor. Can someone please explain this output ?
Thanks.
The base default constructor is called once from the line
All your
Bconstructors call the defaultAconstructor. The last two copy constructors are because of a vector re-allocation. For example, if you addedbefore the
push_backs, they’d go away.The one before that is a copy of the temporary
A(2)in your finalpush_back.