2012年1月6日 星期五

[C++] dynamic_cast

You can use dynamic_cast to identify the type. Then you can do something different according to Derived class with the same Base class pointer.
Just a reminder, when you call destructor of derived class. The vtable pointer and RTTI is no longer exist.
As a result, you will get NULL at second dynamic_cast.
#include <iostream>
#include <cstdio>
#include <cstdlib>

class Base
{
public:
    Base():a(1){};
    ~Base(){};
    virtual void foo() {};
    int a;
};

class Derived : public Base
{
public:
    Derived(){};
    ~Derived(){};
    virtual void foo() {};
};

int main()
{
    void *p = malloc(sizeof(Derived));

    Base *base = new (p) Derived();
    Derived *d = dynamic_cast(base);
    if(d)
        std::cout << "cast ok!\n";     d->~Derived();
    Derived *dd = dynamic_cast(base);
    if(dd)
        std::cout << "cast ok!\n";
    else std::cout << "cast fail!\n";
    return 0;
}