강의

멘토링

커뮤니티

Inflearn Community Q&A

leehoogwan's profile image
leehoogwan

asked

Hong Jung-mo's C++ Programming: Learning by Doing

12.3 override, final, covariant return value

똑같이 쳤는데 결과가 다르게 나와요

Written on

·

290

0

강의 마지막에

b.getThis()->print();

ref.getThis()->print();

이 부분에서 출력하면  b와 ref로 받은 출력값은 각각 B와 A가 나와야 하는데, 저는 B, B가 나옵니다..ㅜ

이유가 멀까요?

C++

Answer 2

2

print() 앞에 virtual을 붙이셨네요. 강의에선 virtual 을 붙이지 않으셨습니다.

0

leehoogwan님의 프로필 이미지
leehoogwan
Questioner

제가 따라 쓴 코드입니다.

#include <iostream>

using namespace std;

class A

{

public:

virtual void print() { cout << "A" << endl; }

virtual A* getThis() 

{

cout << "A::getThis()" << endl;

return this; 

}

};

class B :public A

{

public:

virtual void print(){ cout << "B" << endl; }

virtual B* getThis() 

{

cout << "B::getThis()" << endl;

return this; 

}

};

class C :public B

{

//이와 같이 final을 써주면 더이상 그 아래 상속 받은 class부터는 오버라이딩 하지 못한다.

//void print(int x) final{ cout << "C" << endl; }

};

int main()

{

A a;

B b;

// C c;

A &ref = b;

//ref.print(1);

b.getThis()->print();

ref.getThis()->print();

return 0;

}

출력은

B::getThis()

B

B::getThis()

B

이렇게 나옵니다..

leehoogwan's profile image
leehoogwan

asked

Ask a question