공변 반환형(Covariant Return Type)
- 포인터나 레퍼런스의 전달에서, 상속 관계의 클래스 반환 자료형에 관한 내용이다.
예제
다음은 가상 멤버 함수
getThis
로 받은 포인터를 통해 일반 멤버 함수print
를 호출하는 예제이다.#include <iostream> class A { public: void print() { std::cout << "A" << std::endl; } virtual A* getThis() { std::cout << "A::getThis()" << std::endl; return this; } }; class B : public A { public: void print() { std::cout << "B" << std::endl; } virtual B* getThis() { std::cout << "B::getThis()" << std::endl; return this; } }; int main() { using namespace std; A a; B b; A& ref = b; b.getThis()->print(); ref.getThis()->print(); cout << typeid(b.getThis()).name() << endl; cout << typeid(ref.getThis()).name() << endl; } /* stdout B::getThis() B B::getThis() A class B * class A * */
stdout
에서 볼 수 있듯이,ref.getThis()
는B::getThis()
를 호출하고B*
형태의 주소를 반환한다.하지만
ref
의 자료형이A
클래스의 레퍼런스이므로,A*
형태의 주소로 인식되어A::print()
가 실행되는 것이다.typeid(ref.getThis()).name()
함수의 결과가class A *
형태인 것으로도 유추할 수 있다.
'C++ > Class' 카테고리의 다른 글
C++ 정적 바인딩 (Static Binding) (0) | 2021.03.20 |
---|---|
C++ 가상 소멸자 (0) | 2021.03.20 |
C++ Override, Final (0) | 2021.03.20 |
C++ 가상 함수와 다형성 (virtual) (0) | 2021.03.20 |
C++ 다형성의 기본 개념 (0) | 2021.03.20 |