본문 바로가기

Robotics/Software Tech.

[C++]Dynamic cast 사용 방법예


class CMyClass
{
       virtual void Foo()  {}
};

class CMyDerivedClass : public CMyClass
{
        void Foo() {}
} ;

// Declare a variable of
CMyDerivedClass* myDerivedClassObject = new CMyDerivedClass();

// Call Foo() of derived class
myDerivedClassObject->Foo();

// Call Foo() of the base class
CMyClass* myClass = dynamic_cast<CMyClass*>(myDerivedClassObject);

// Make sure that our program won’t crash
assert(myClass);
myClass->Foo(); // Calls the Foo() in the base class