Vasile Turcu Vasile Turcu - 3 months ago 21
C++ Question

C++ Copy Constructor Error

Say I have the following piece of code:

class C1{
int x, y;

public:

C1(int a, int b):x(a),y(b)
{
cout<<"const normal C1"<<endl;
}
};

class C2 : protected C1
{
int x, y;
const int z;

public:
C2(int u, int v, int w):C1(u,v),z(w)
{
cout<<"constr normal C2"<<endl;
}
C2(const C2 &a,int u, int v, int w):C1(u,v),z(w)
{
cout<<"cpy constr C2"<<endl;
}
};

int main(){
C2 a(2,3,4);
C2 b=a;
}


When I create the object b, the copy constructor is supposed to be called instead of the normal constructor, but it is not. Now I know that a copy constructor should look like


C(C const& obj){...}


where C is a class, but in this case, I need the other parameters for C1's constructor. Now, my question is, what have I done wrong, or what can I do in order to make the copy constructor work properly?

Answer

Your second constructor is not a copy constructor. A constructor is only a copy constructor if it can be called with a single argument which is the object to be copied from.

Why not:

C2(const C2 &a):C1(static_cast<const C1&>(a)), z(a.z)
{
    cout<<"cpy constr C2"<<endl;
}

Note that

  1. this copy constructor is practically the same as the compiler generated one.
  2. the static_cast is unnecessary (I put it in for clarity).
Comments