I saw the following question and I asked myself if there is a better way to address this problem, so there is no need for a cast. Consider the following code:
#include <iostream>
class Base
{
    public:
        virtual ~Base() {}
};
class Derived : public Base
{
    protected:
        int someVar = 2;
    public:
        int getSomeVar () {return this->someVar;}   
};
int main()
{
    Base    B = Base(); 
    Derived D = Derived();
    Base *PointerToDerived  = &D;
    Base *PointerToBase     = &B;
    std::cout << dynamic_cast<Derived*>(PointerToDerived)->getSomeVar() << "\n"; //this will work
    std::cout << dynamic_cast<Derived*>(PointerToBase)->getSomeVar() << "\n"; //this will create a runtime error
    return 0;
}
Is there a better way to design this, so no cast is needed and runtime errors like this can be avoided?
 
     
     
     
     
    