In one header file I have:
#include "BaseClass.h"
// a forward declaration of DerivedClass, which extends class BaseClass.
class DerivedClass ;
class Foo {
DerivedClass *derived ;
void someMethod() {
// this is the cast I'm worried about.
((BaseClass*)derived)->baseClassMethod() ;
}
};
Now, DerivedClass is (in its own header file) derived from BaseClass, but the compiler doesn’t know that at the time it’s reading the definition above for class Foo. However, Foo refers to DerivedClass pointers and DerivedClass refers to Foo pointers, so they can’t both know each other’s declaration.
First question is whether it’s safe (according to C++ spec, not in any given compiler) to cast a derived class pointer to its base class pointer type in the absence of a full definition of the derived class.
Second question is whether there’s a better approach. I’m aware I could move someMethod()’s body out of the class definition, but in this case it’s important that it be inlined (part of an actual, measured hotspot – I’m not guessing).
It may work, but the risk is huge.
The problem is that most of the times
Derived*andBase*will indeed have the same value under the hood (which you could print). However this is not true as soon as you have virtual inheritance and multi-inheritance and is certainly not guaranteed by the standard.When using
static_castthe compiler performs the necessary arithmetic (since it knows the layout of the class) to adjust the pointer value. But this adjustment is not performed byreinterpret_castor the C-style cast.Now, you could perfectly rework your code like so:
Anyway: you are using a pointer to
Derived, while it’s okay there is a number of gotchas you should be aware of: notably if you intend tonewan instance of the class it will be necessary for you to redefine theCopy Constructor,Assignment OperatorandDestructorof the class to properly handle the pointer. Also make sure to initialize the pointer value in everyConstructor(whether to NULL or to an instance ofDerived).It’s not impossible but document yourself.