#include #include using namespace std; class BaseT { public: BaseT(string s): name(s){ cout << "In the base class constructor" << endl; } virtual ~BaseT() { cout << "In the base class destructor " << endl; } virtual void Method1() { cout << "In base class method 1" << endl; } virtual void Method2() { cout << "In base class method 2" << endl; } void Method3() { cout << "In base class method 3" << endl; } void Method4() { cout << "In base class method 4" << endl; } private: string name; }; class DerivedT: public BaseT { public: DerivedT(string s): BaseT(s){ cout << "In the DerivedT class constructor" << endl; method3Data = 100; } ~DerivedT() { cout << "In the DerivedT class destructor " << endl; } void Method1() override { cout << "In DerivedT class method 1" << endl; } void Method3() { cout << "In DerivedT class method 3" << endl; cout << "\tThe data is " << method3Data << endl; } private: int method3Data; }; int main() { BaseT * base; DerivedT * derived; // case 1 point a base at a base. cout << "\t\tPoint a base at a base (Currently base)" << endl; base = new BaseT("base"); base ->Method1(); base ->Method2(); base ->Method3(); base ->Method4(); cout << endl << endl; cout << "\t\tPointing a derived at a base (Currently Base) " << endl; derived= dynamic_cast(base); if (derived != nullptr) { cout << "The cast was successful " << endl; } else { cout << "The cast failed " << endl; } delete base; cout << endl << endl << endl; // case 2, point a base at a derived; cout << "\t\tPointing a base at a derived (Currently derived)" << endl; base = new DerivedT("derived"); base ->Method1(); base ->Method2(); base ->Method3(); base ->Method4(); cout << endl << endl << endl; cout << "\t\tPointing the derived at that same thing (Currently derived)." << endl; derived= dynamic_cast(base); derived ->Method1(); derived ->Method2(); derived ->Method3(); derived ->Method4(); delete base; cout << endl << endl << endl; // case 3 pointing a derived at a derived. cout << "\t\tPointing the derived at a derived. (Currently Derived)" << endl; derived = new DerivedT("derived"); derived ->Method1(); derived ->Method2(); derived ->Method3(); derived ->Method4(); cout << endl << endl << endl; cout << "\t\tPointing the base at that derived (Currently Derived)" << endl; base = dynamic_cast (derived); base ->Method1(); base ->Method2(); base ->Method3(); base ->Method4(); delete base; cout << endl << endl << endl; cout << "\t\tBad bad bad, forcing a base to be a Derived" << endl; derived = reinterpret_cast(new BaseT("base")); derived ->Method1(); derived ->Method2(); derived ->Method3(); derived ->Method4(); delete derived; return 0; }