class Child : public Mother { virtual someThing() {} //if not virtual : cannot dynamic_cast ... (source type is not polymorphic) }
Mother* pn = new Child; Child* pb = dynamic_cast<Child*>(pn);
#include <iostream> using namespace std; #define debug(x) cerr<<"# " <<(x)<<endl;
class M { public: M() : name_(0){} virtual ~M() { if (name_ ) delete[[]] name_;} char* name_; };
class D : public M { public: virtual ~D() {} //virtual is needed to set the class polymorphic };
class S : public M { public: virtual ~S() {} //virtual is needed to set the class polymorphic };
void f(M* m) { debug("-f M*"); } void f(D* m) { debug("-f D*"); }
int main() { debug("+ main"); M m; f(&m); // M : ok
D d; f(&d); // D : ok
S s; f(&s); // M : ok
M* pm = new D; f(pm); // M : Err, we want D
debug("Rtti"); if ( D* pd = dynamic_cast<D*>(pm) ) { f(pd); } // D : ok debug("test types one after one... "); if ( S* ps = dynamic_cast<S*>(pm) ) { f(ps); } // nothing
debug("- main"); return 0; }
While it is not possible in C :
struct M { char* name_; };
struct D { struct M* super_; };
void f(struct M* m) { debug("-f M*"); } //void f(struct D* m) { debug("-f D*"); } //mainc.c:14: error: conflicting types for `f' //mainc.c:13: error: previous declaration of `f'