9. 가상(Virtual)의 원리와 다중상속
출처: 윤성우 열혈강의 C++ 예제코드
9.1. 멤버함수와 가상함수의 동작원리
- 오버라이딩 시점에 따른 가상함수 호출
#include <iostream>
using namespace std;
class AAA
{
private:
int num1;
public:
virtual void Func1() { cout<<"Func1"<<endl; }
virtual void Func2() { cout<<"Func2"<<endl; }
};
class BBB: public AAA
{
private:
int num2;
public:
virtual void Func1() { cout<<"BBB::Func1"<<endl; }
void Func3() { cout<<"Func3"<<endl; }
};
int main(void)
{
AAA * aptr=new AAA();
aptr->Func1();
BBB * bptr=new BBB();
bptr->Func1();
return 0;
}
9.2. 다중상속(Multiple Inheritance)에 대한 이해
- 가상상속을 이용하여 중복상속 피하기
#include <iostream>
using namespace std;
class Base
{
public:
Base() { cout<<"Base Constructor"<<endl; }
void SimpleFunc() { cout<<"BaseOne"<<endl; }
};
class MiddleDrivedOne : virtual public Base
{
public:
MiddleDrivedOne() : Base()
{
cout<<"MiddleDrivedOne Constructor"<<endl;
}
void MiddleFuncOne()
{
SimpleFunc();
cout<<"MiddleDrivedOne"<<endl;
}
};
class MiddleDrivedTwo : virtual public Base
{
public:
MiddleDrivedTwo() : Base()
{
cout<<"MiddleDrivedTwo Constructor"<<endl;
}
void MiddleFuncTwo()
{
SimpleFunc();
cout<<"MiddleDrivedTwo"<<endl;
}
};
class LastDerived : public MiddleDrivedOne, public MiddleDrivedTwo
{
public:
LastDerived() : MiddleDrivedOne(), MiddleDrivedTwo()
{
cout<<"LastDerived Constructor"<<endl;
}
void ComplexFunc()
{
MiddleFuncOne();
MiddleFuncTwo();
SimpleFunc();
}
};
int main(void)
{
cout<<"객체생성 전 ..... "<<endl;
LastDerived ldr;
cout<<"객체생성 후 ..... "<<endl;
ldr.ComplexFunc();
return 0;
}