본문 바로가기
프로그래밍 언어/C++

[C++] 상속과 복사/대입 연산자

by 까망 하르방 2025. 3. 14.
반응형

상속과 복사/대입 연산자

부모-자식 상속에서 컴파일러가 알아서 만들어주는 Case가 많은데

이중에서 복사 생성자 / 대입연산자 주의 사항이 있다.

 

#include <iostream>

class Base
{
	int b;
public:
	Base() = default;
	Base(int n) : b{ n } {}

	int Get() { return b; };
};

class Derived : public Base
{
	int d;
public:
	Derived(int n1, int n2) : Base{ n1 }, d{ n2 } {}
	Derived(const Derived& other)
		: d(other.d)
	{
	}
};

int main()
{
	
	Derived d1(10, 20);
	Derived d2 = d1;

	printf("d2.b = %d\n", d2.Get()); // ??
}



컴파일러가 알아서 Base 클래스의 디폴트 생성자(Base()) 호출하여
변수 b가 제대로 할당되지 않았다.

 

 

[예제] 기반 클래스 복사 생성자 명시

#include <iostream>

class Base
{
	int b;
public:
	Base() = default;
	Base(int n) : b{ n } {}

	int Get() { return b; };
};

class Derived : public Base
{
	int d;
public:
	Derived(int n1, int n2) : Base{ n1 }, d{ n2 } {}
	Derived(const Derived& other)
		: Base(other), d(other.d) // 기반 클래스의 복사 생성자 명시
	{
	}
};

int main()
{
	
	Derived d1(10, 20);
	Derived d2 = d1;

	printf("d2.b = %d\n", d2.Get()); // 10
}



[예제] 기반 클래스 대입 연산자 명시

대입 연산자 직접 구현에서도 마찬가지로
기반 클래스의 대입 연산자를 명시해주어야 한다.

#include <iostream>

class Base
{
	int b;
public:
	Base() = default;
	Base(int n) : b{ n } {}

	int Get() { return b; };
};

class Derived : public Base
{
	int d;
public:
	Derived(int n1, int n2) : Base{ n1 }, d{ n2 } {}
	Derived(const Derived& other)
		: Base(other), d(other.d)
	{
	}

	Derived& operator=(const Derived& other)
	{
		if (&other == this) return *this;

		Base::operator=(other); // 기반 클래스 대입 연산자 명시

		d = other.d;
		return *this;
	}
};

int main()
{
	Derived d1(10, 20);
	Derived d2(0, 0);
	
	d2 = d1;

	printf("d2.b = %d\n", d2.Get());
}
반응형

댓글