#include #include #include using namespace std; class Base { public: virtual ~Base() = default; virtual void Speak() { cout << " I have no idea who I am , I can't speak" << endl; } }; class Dog: public Base { public: void Speak() { cout << "Woof !" << endl; barks++; cout << "For the " << barks << " time. " << endl; } void FleaStory(){ cout << "This dog has " << flea_names.size() << " fleas" << endl; for (auto x: flea_names) { cout << x << "-dogEater " ; } cout << endl; cout << "That comes from barking " << barks << endl; } private: vector flea_names = {'A','B','C'}; int barks = 0; }; class Cat: public Base { public: void Speak() { cout << "Meow!" << endl; mews++; cout << " For the " << mews << " time" << endl; } void FleaStory(){ cout << "This cat has " << flea_names.size() << " fleas" << endl; for (auto x: flea_names) { cout << x << "-catEater " ; } cout << endl; cout << "That comes from mewing " << mews << endl; } private: int mews = 0; vector flea_names = {'X','Y','Z'}; }; int main() { Base * basePtr = new Dog; Dog * dogPtr; Cat * catPtr; basePtr ->Speak(); cout << endl; cout << "Dynamic cast to dog* " << endl; dogPtr = dynamic_cast (basePtr); if (dogPtr != nullptr) { dogPtr ->Speak(); dogPtr ->FleaStory(); cout << endl; } else { cout << "failed" << endl; } cout << endl; cout << "Dynamic cast to cat* " << endl; catPtr = dynamic_cast (basePtr); if (catPtr != nullptr) { catPtr ->Speak(); catPtr ->FleaStory(); cout << endl; } else { cout << "failed" << endl; } cout << endl; cout << "Static cast from dog* to cat *" << endl; catPtr = static_cast(basePtr); catPtr ->Speak(); catPtr ->FleaStory(); cout << endl; cout << "reinterpret cast to cat* " << endl; catPtr = reinterpret_cast (basePtr); catPtr ->Speak(); catPtr ->FleaStory(); cout << endl; delete basePtr; return 0; }