반응형

자식 클래스에서 특별히 필요하지 않으면 복사 생성자를 생성하지 않고 디폴트 복사 생성자를 이용할 수 있다. 컴파일러는 복사 생성자가 정의되지 않으면 알아서 디폴트 복사 생성자를 생성한다. 그러나 깊은 복사를 위해 직접적으로 복사 생성자를 정의한다고 할 때, 자식 클래스에서 부모 클래스의 복사 생성자를 명시적으로 호출해주지 않을 경우 부모 클래스의 멤버에 대해 복사 생성자가 호출되지 않고 디폴트 생성자가 호출되는데 그친다.


#include <iostream>
 
using namespace std;
 
class Parent
{
private:
    int x;
 
public:
    Parent(int n = 0) : x(n) {}
    Parent(const Parent& copy) : x(copy.x) {}
 
    int getX() { return x; }
};
 
class Child : public Parent
{
private:
    int y;
 
public:
    Child(int n1 = 0, int n2 = 0) : Parent(n1), y(n2) {}
    Child(const Child& copy) : y(copy.y) {}
 
    int getY() { return y; }
};
 
int main(void)
{
    Child c1(1);
    Child c2(c1);
     
    cout << c1.getX() << ',' << c1.getY() << endl;
    cout << c2.getX() << ',' << c2.getY() << endl;
 
    return 0;
}



1,0

0,0


 부모 클래스의 멤버에 대해 정상적으로 복사 생성자가 호출되기 위해 자식 클래스의 복사 생성자에서 명시적으로 부모 클래스의 복사 생성자를 호출해주자.


1
Child(const Child& copy) : Parent(copy), y(copy.y) {}

1,0

1,0


출처 http://wonthing86.tistory.com/59

반응형

+ Recent posts