ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • RTTI : Run-time type information 사용예
    C++ 2014. 1. 18. 00:25

    #include <iostream>

    class Base
    {
    public:
     Base() { } 
     virtual ~Base() { }

     virtual void hello() 
     {
      std::cout << "in Base";
     }
    };

    class Derived : public Base
    {
    public:
     void hello() 
     {
      std::cout << "in Derived";
     }

     void Bye()
     {
      std::cout << "out Derived";
     }
    };

       

    int _main() {
     // 부모객체에 자식클래스 동적할당
     Base* basePointer = new Derived();


    //To find whether basePointer is pointing to Derived type of object
     Derived* derivedPointer = dynamic_cast<Derived*>(basePointer);

     // 다이나믹 캐스트가 성공했다면
     if (derivedPointer != nullptr)
     {
      std::cout << "basePointer is pointing to a Derived class object"; //Identified
     }
     // 다이나믹 캐스트가 실패했다면(derivedPointer  객체에 널값이 들어감.)
     else
     {
      std::cout << "basePointer is NOT pointing to a Derived class object";
     }

     //Requires virtual destructor 
     delete basePointer;
     basePointer = nullptr;

     return 0;


    }

    RTTI의 주사용목적은 부모객체로 자식클래스의 함수를 동적으로 호출하고자 할때 유용합니다.

    다이나믹 캐스트를 통해 만약 basePointer객체에 Derived 객체가 있다면 하향형변환을 통해 Derived객체를 리턴하게되고

    만약 Derived 객체가 없다면 NULL 값을 리턴하게 되므로 널값체크만 하면 됩니다.

    더 풀어서 이야기하자면 다이나믹캐스트를 했을때 형변환하려는 객체 basePointer가 자식클래스로 Derived 클래스를 가지고 있다면

    Derived를 리턴 그렇지 않다면 NULL값을 리턴하게 되는것입닌다.

    RTTI를 쓰기위해선 꼭 부모클래스에 최소한 virtual 함수가 하나 이상은 있어야합니다.

    사실 polymorphism을 이용하는 것이 RTTI를 사용하는 것보다 바람직하다.

    예)

    class Base
    {
    public:
     Base() { } 
     virtual ~Base() { }

     virtual void hello() 
     {
      std::cout << "in Base";
     }

    // 아래와 같이 Derived 함수에 있던 Bye() 함수를 부모클래스에 가상함수로 정의

    virtual void Bye(){}
    };

     RTTI를 무분별하게 사용할 경우(하나의 함수안에서 다른 자식클래스로 여러번 캐스팅이 이루어질경우) 현재 부모객체가 어떤 자식클래스로 캐스팅되어있는지 모르게 될 경우가 있습니다.

    'C++' 카테고리의 다른 글

    Constructor 와 메모리  (0) 2014.02.12
    Cast 연산자  (0) 2014.01.22
    Template 사용  (0) 2014.01.16
    Friend의 사용시기  (0) 2014.01.14
    Overloading과 Overriding의 차이  (0) 2014.01.14
Designed by Tistory.