Sunday, 8 September 2013

Why does the C++ copy constructor behave differently when calling its child copy constructor?

Why does the C++ copy constructor behave differently when calling its
child copy constructor?

I have the following toy class A and its child B:
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
A():a(1){cout<<"A default constructor..."<<endl;}
A(int i):a(i){cout<<"A non-default constructor..."<<endl;}
A(const A &ao){cout<<"A copy constructor..."<<endl; a=ao.a;}
};
class B:public A
{
private:
int b;
public:
B(int i,int j):A(i),b(j){cout<<"B constructor..."<<endl;}
//B(const B &bo){cout<<"B copy constructor... "<<endl; b=bo.b;}
void print(){cout<<endl<<"class B, a: "<<a<<" b: "<<b<<endl<<endl;}
};
int main()
{
B b1(3,8);
b1.print();
B b2=b1;
b2.print();
}
I found that if I don't provide a copy constructor for class B, the
compiler will synthesize one for me, and that one uses the copy
constructor I provided for class A. However, if I do provide a copy
constructor for class B, where I don't explicitly call the copy
constructor for the base class A (see code), the compiler will call the
default CONSTRUCTOR of class A? Why is that?

No comments:

Post a Comment