본문 바로가기

etc.

[C++] virtual 과 오버라이딩

반응형

 

Kim is a freshman
Score is 80

 

흔히 아는 것처럼

main문에서 실행되는 PrintScore(), PrintStudent() 함수는

각각 CollegeStudent, Freshman 자식 클래스에서 함수가 오버라이딩 되어 출력문이 바뀌어 출력된다.

 




 

Kim is a student; Lee is a freshman; Park is a sophomore;
Kim is a student; Lee is a student; Park is a student;

 

이 문제는 오버라이딩의 문제가 아니다

 

main문에서 각각의 class에서 Print()의 함수를 호출한다
Print()는 Freshman, Sophomore 클래스에서 오버라이딩 한 함수가 아닌 Student 클래스의 함수이다

Print() 함수에서는 PrintName(), PrintStudent() 함수를 호출하는데,

PrintName()는 Student 클래스의 함수이고, PrintStudent()는 각각의 클래스에 정의되어 있다

이 때 virtual 을 사용하게 되면 동적할당을 통해 부모(Student)가 아닌 자식(Freshman, Sophomore) 의 함수를 호출하게 되는 것입니다

하지만 virtual을 삭제한다면, 정적할당이 되어 부모(Student)에서 함수를 찾아 호출하게 되어 내용이 바뀌게 출력되지 않는다

반응형