Safe to cast pointer to a forward-declared class to its true base class in C++?
- by Matt DiMeo
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).