#include #include using namespace std; class Base { public: virtual ~Base()=default; virtual void Print() { cout << "a = " << a << endl; } private: int a = 7; }; class Derived1: public Base { public: Derived1():id(++count){}; virtual void Print() { Base::Print(); cout << "b = " << b << endl; } int ID(void) const { return id; } vector & Data(void) { return data; } private: int b = 9; static inline int count = 0; vector data{99, 99, 99, 99}; const int id; }; void PrintMe( Derived1 * derivedPtr){ if (derivedPtr == nullptr) { cout << "Nope, it is a null pointer!" << endl; } else { derivedPtr->Print(); { cout << "My ID is " << derivedPtr->ID() << endl; vector & d = derivedPtr->Data(); for(auto x: d) { cout << x << " " ; } } cout << endl; } } int main() { Base a; Derived1 b; Base * basePtr = nullptr; Derived1 * derivedPtr = nullptr; cout << "The base class is " << endl; a.Print(); cout << endl; cout << "The derived class is " << endl; b.Print(); cout << endl; // allowed and should work fine. cout << "basePtr at Derived print call " << endl; basePtr = new Derived1; basePtr->Print(); cout << endl; cout << "derivedPtr at Derived print after cast from base call " << endl; //derivedPtr = basePtr; derivedPtr = static_cast(basePtr); PrintMe(derivedPtr); delete derivedPtr; basePtr = new Base; cout << "basePtr at base print call " << endl; basePtr->Print(); cout << endl; // this is bad. cout << "derivedPtr at base print after cast from base call " << endl; derivedPtr = static_cast(basePtr); //PrintMe(derivedPtr); // this is safe derivedPtr = dynamic_cast(basePtr); PrintMe(derivedPtr); return 0; }