코딩중 궁금하여 Test 해본 코드이다. 순수가상함수가 있다고 할때 이를 속상받는 클래스에서 순수가상함수를 재정의할때 반환타입을 다르게 할 수 있는가라는 스스로의 질문에 대한 정리이다.
기본적으로 Base가 되는 클래스 둘이 있는데 아래와 같다.
class ReturnType {
protected:
int x;
public:
ReturnType(int x) {
this->x = x;
}
virtual int GetValue() {
return x;
}
};
class Base {
public:
virtual ReturnType* Get(int a, int b) = 0;
};
클래스 Base는 Get이라는 순수가상함수를 가지고 있고 반환값으로 ReturnType을 갖는다. 여기서 따져보고 싶은 것은 Base의 Get이라는 순수가상함수의 반환 Type을 다르게 하여 선언할 수 있냐는 것이다. 대답은 “않된다”이지만 반환 Type도 OO의 다형성을 활용해서 다르게 선언할 수 있다는 것이다. 아래를 보자.
class ReturnType2 : public ReturnType {
public:
ReturnType2(int x) : ReturnType(x) {
}
virtual int GetValue() {
return x*x;
}
};
class Derive1 : public Base {
public:
virtual ReturnType2* Get(int a, int b) {
ReturnType2* pRT = new ReturnType2(a+b);
return pRT;
}
};
class Derive2 : public Base {
public:
virtual ReturnType* Get(int a, int b) {
ReturnType* pRT = new ReturnType(a*2+b*2);
return pRT;
}
};
ReturnType으로부터 상속받은 ReturnType2 클래스가 있으며 Base로부터 상속받은 Derive1과 Derive2가 있다. 분명한것은 GetValue라는 순수가상함수의 반환타입이 상속받은 Base와 다르다는 점이다. 하지만 완전이 다른것은 아니고 반환타입이 상속관계를 갖는다. 이런 상속관계가 반환타입을 다르게 할 수 있는 이유가 되는 것이다.
