I have run into a bit of a tricky problem in some C++ code, which is most easily described using code. I have classes that are something like:
class MyVarBas
The correct way to do this is to have the variable only in the base class. As the derived class knows it must be of dynamic type MyVar, this is totally reasonable:
class MyClass : public MyBase
{
public:
MyClass(MyVar* v) : MyBase(v) {}
MyVar* GetVar() { return static_cast(MyBase::GetVar()); }
}
Since MyVar is derived from MyVarBase, the different return-types of GetVar would still work if GetVar was virtual (as is the case here). Note that with that method, there must be no function in MyBase that can reset the pointer to something different, obviously.
Note that static_cast is the right cast in that case. Using dynamic_cast, as proposed by one commenter, will tell the readers and users of GetVar that MyBase::GetVar() could return a pointer to an object not of type MyVar. But that doesn't reflect our intention, as you only ever pass MyVar. To be consequent is the most important thing in software development. What you could do is to assert it is non-null. It will abort at runtime with an error-message in debug-builds of your project:
MyVar* GetVar() {
assert(dynamic_cast(MyBase::GetVar()) != 0);
return static_cast(MyBase::GetVar());
}