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*
and Base*
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_cast
the compiler performs the necessary arithmetic (since it knows the layout of the class) to adjust the pointer value. But this adjustment is not performed by reinterpret_cast
or the C-style cast.
Now, you could perfectly rework your code like so:
// foo.h
class Derived;
class Foo
{
public:
void someMethod();
private:
Derived* mDerived;
};
// foo.cpp
#include "myProject/foo.h"
#include "myProject/foo.cpp"
void Foo::someMethod() { mDerived->baseClassMethod(); }
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 to new
an instance of the class it will be necessary for you to redefine the Copy Constructor
, Assignment Operator
and Destructor
of the class to properly handle the pointer. Also make sure to initialize the pointer value in every Constructor
(whether to NULL or to an instance of Derived
).
It's not impossible but document yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With