// dynamic_cast is used to cast a pointer to a base class object // to a pointer to a derived class. // // Generally, using dynamic_cast to determine the real type of // an object is the WRONG way to do it. Rather, have a method // that tells you what you want to know. In the example below, // a method called carnivore() would make more sense. #include using namespace std; class Relative { public: Relative(const string &who) : name(who) { } virtual const string &get_name() const { return name; } private: const string name; }; class Father : public Relative { public: Father(const string &who) : Relative(who) { } void rake_leaves() { } }; class Mother : public Relative { public: Mother(const string &who) : Relative(who) { } void practice_spelling() { } }; class Uncle : public Relative { public: Uncle(const string &who) : Relative(who) { } void play_cribbage() { } }; void greet(Relative *r) { // Is it Mom? Mother *m = dynamic_cast(r); // m is non-nullptr for Mom, nullptr for everybody else. cout << (m ? "Kiss " : "Embrace ") << r->get_name() << "!\n"; } int main() { Father f("John"); // My father Mother m("Helen"); // My mother Uncle u("Walt"); // My uncle greet(&f); // Say hello to Dad greet(&m); // Say hello to Mom greet(&u); // Say hello to Uncle Walt }