본문 바로가기

study

C++ 의 virtual 키워드

가상함수란?

- 기본 클래스에 virtual 키워드를 이용하여 정의된 멤버함수를 파생 클래스에서 재정의할 때

   기본 클래스의 멤버함수를 말한다.

- 동적 바인딩을 통한 실시간 다형성이 가능하다.

- 호출된 멤버함수의 결정이 컴파일 타임이 아닌 실행시간에 결정된다.


-> 코딩 연습

※ 직접 코딩 해 보길 바란다.

======================================================

일반적인 멤버함수의 재정의 예제(정적 바인딩)

#include <iostream.h>


class Parent
{
public:
    void Print()
    {
        cout << "I'm Print..." << endl;
    }
};


class Child : public Parent
{
public:
    void Print()
    {
        cout << "I'm Child..." << endl;
    }
};


void main()
{
    Parent objParent;
    Child objChild;


    objParent.Print();

    objChild.Print();
}

======================================================


======================================================

객체 포인터를 사용하는 경우의 재정의 예제

#include <iostream.h>


class Parent
{
public:
    void Print()
    {
        cout << "I'm Print..." << endl;
    }
};


class Child : public Parent
{
public:
    void Print()
    {
        cout << "I'm Child..." << endl;
    }
};


void main()
{
    Parent objParent;
    Child objChild;


    Parent *ptr;


    ptr = &objParent;
    ptr->Print();


    ptr = &objChild;
    ptr->Print();                              Parent의 Print()가 출력된다.
    ((Child *)ptr)->Print();               Child의 Print()가 출력된다.
}

======================================================


======================================================

가상함수를 사용한 재정의 예제(동적 바인딩)

#include <iostream.h>


class Parent
{
public:
    virtual void Print()
    {
        cout << "I'm Print..." << endl;
    }
};


class Child : public Parent
{
public:
    void Print()
    {
        cout << "I'm Child..." << endl;
    }
};


class AnotherChild : public Parent
{
public:
    void Print()
    {
        cout << "I'm Another Child..."
    }
};


void main()
{
    Parent objParent;
    Child objChild;


    Parent *ptr;


    ptr = &objParent;
    ptr->Print();


    ptr = &objChild;
    ptr->Print();                         Child의 Print() 출력된다.
    ((Child *)ptr)->Print();          Child의 Print() 출력된다.


    int i;
    AnotherChild objAnother;


    cout << "Enter Number 1 or 2 ";
    cin >> i;


    if(i == 1)
        ptr = &objChild;
    else
        ptr = &objAnother;


    ptr->Print();                  어떤 객체의 Print()인지 결정할 수 없다.
}

======================================================


 - referenced from http://cafe.naver.com/zzangprograming/45 -