728x90
https://www.ecourse.co.kr/courses/cpp_designpattern/lessons/virtual-function-2/#tab-201441
#include <string>
class Animal
{
std::string name;
int age;
public:
void Cry() { }
};
class Dog : public Animal
{
int color;
public:
void SetColor(int c) { color = c; }
};
int main()
{
Dog dog;
Dog* p1 = &dog;
int* p2 = &dog; //error
Animal* p3 = &dog;
return 0;
}
Animal을 상속받는 Dog가 있을 때, Dog 객체의 주소를 Animal 포인터로 가리킬 수 있다. 이처럼 기반 클래스의 포인터로 파생 클래스를 가리키는 것을 upcasting이라 한다.
upcasting이 가능한 이유는, 메모리 레이아웃 상에서 p3를 따라갔을 때 실제로 Animal이 있기 때문이다.
upcasting은 동종(동일 기반 클래스로 부터 파생된 클래스)을 처리하는 함수, 혹은 동종을 보관하는 컨테이너에서 활용될 수 있다.
int main()
{
...
p3->Cry();
p3->SetColor(0); //error
static_cast<Dog*>(p3)->SetColor(0);
return 0;
}
한편 p3는 SetColor를 호출할 수 없는데, 기반 클래스 포인터로는 기반 클래스 멤버만 접근할 수 있기 때문이다. 따라서 파생 클래스의 고유 멤버에 접근하려면 명시적으로 캐스팅(static_cast) 해야 한다.
728x90
'Programing > Design Pattern' 카테고리의 다른 글
template method (0) | 2025.02.10 |
---|---|
adapter #1 (0) | 2025.02.09 |
shape #2 (0) | 2025.01.26 |
dynamic_casting (0) | 2025.01.17 |
constructor (0) | 2025.01.16 |