본문 바로가기
코드/C++

함수 재정의와 함수 오버라이딩(virtual)

by bongin 2022. 7. 27.
728x90
반응형

1.함수 재정의

#include <iostream>
using namespace std;

class Base
{
	public:
	① virtual void f() {cout << "Base::f() called" << endl;}
};

class Derived : public Base
{
	public:
	② virtual void f() {cout << "Derived::f() called" << endl;} //여기 }뒤에 뭐 붙어 있음 제거
};

void main()
{
	Derived d;
	Derived *pDer;
	pDer = &d;
	pDer->f(); //실행 결과 Derived::f() called

	Base* pBase;
	pBase = pDer;
	pBase->f(); //실행 결과 Base::f() called
}

Derived d;
pDer = &d;
pBase = pDer;
pBase->f();

pBase (부모 객체의 포인터)에 상속 객체 d의 주소가 담겨 있으므로 
Derived::f()가 실행되어야 하나,

(컴파일 당시에는 내용에는 신경 쓰지 않음)
부모 객체인 pBase를 통해 pBase->f()를 호출했다고 판단하여
Base::f()가 실행된다.

 

 

 

2. 함수 오버라이딩

#include <iostream>
using namespace std;

class Base
{
	public:
	① void f() {cout << "Base::f() called" << endl;}
};

class Derived : public Base
{
	public:
	② void f() {cout << "Derived::f() called" << endl;} //여기 }뒤에 뭐 붙어 있음 제거
};

void main()
{
	Derived d;
	Derived *pDer;
	pDer = &d;
	pDer->f(); //실행 결과 Derived::f() called

	Base* pBase;
	pBase = pDer;
	pBase->f(); //실행 결과 Base::f() called
}

Derived d;
pDer = &d;
pBase = pDer;
pBase->f();

실행 시점에 pBase (부모 객체의 포인터)가 가리키는 객체는 Derived d이고,
최초 pBase->f()는 Base의 f()에 대한 호출로 인지되지만 이를 Derived의 f()로 연결시킴

최종적으로 동적 바인딩을 통해 Derived의 f()가 호출

728x90
반응형

'코드 > C++' 카테고리의 다른 글

GetPixel  (0) 2022.07.27
참조 (Ampersand)  (0) 2022.07.27
pixel color fast  (0) 2022.07.27
section .bss  (0) 2022.07.27
CMD ASLR : 임의 기준 주소  (0) 2022.07.27

댓글