Reputation: 127
-EDIT-
Thanks for the quick response, I'd been having really weird problems with my code and I changed my casts to dynamic_cast and its working perfectly now
-ORIGINAL POST-
Is it safe to cast a pointer of one base class to another base class? To expand on this a bit, will the pointer I've marked in the following code not result in any undefined behavior?
class Base1
{
public:
// Functions Here
};
class Base2
{
public:
// Some other Functions here
};
class Derived: public Base1, public Base2
{
public:
// Functions
};
int main()
{
Base1* pointer1 = new Derived();
Base2* pointer2 = (Base2*)pointer1; // Will using this pointer result in any undefined behavior?
return 1;
}
Upvotes: 9
Views: 2766
Reputation: 506
You should use dynamic_cast
operator. This function returns null if types are incompatible.
Upvotes: 1
Reputation: 234434
Will using this pointer result in any undefined behavior?
Yes. The C-style cast will only try the following casts:
const_cast
static_cast
static_cast
, then const_cast
reinterpret_cast
reinterpret_cast
, then const_cast
It will use reinterpret_cast
and do the wrong thing.
If Base2
is polymorphic, i.e, has virtual
functions, the correct cast here is dynamic_cast
.
Base2* pointer2 = dynamic_cast<Base2*>(pointer1);
If it doesn't have virtual functions, you can't do this cast directly, and need to cast down to Derived
first.
Base2* pointer2 = static_cast<Derived*>(pointer1);
Upvotes: 13