How do I cast a struct to one of its base types?
In c# you can do that with the keyword "as" like Entity as Monster
. How can I do this in c++?
This is my structure:
struct Entity
{
USHORT X;
USHORT Y;
UINT Serial;
USHORT SpriteID;
};
struct Monster : Entity
{
UINT UNKNOWN;
BYTE Direction;
USHORT Type;
};
struct Item : Entity
{
BYTE UNKNOWN1;
USHORT UNKNWON2;
};
struct NPC : Entity
{
UINT UNKNOWN1;
BYTE Direction;
BYTE UNKNOWN2;
BYTE NameLength;;
byte Name[];
};
In C++, this possibility exists only for pointers to objects of polymorphic types (i.e. types with at least one virtual function). You can do it with a dynamic_cast<PtrType>
.
Here is a complete example (also on ideone):
#include <iostream>
using namespace std;
struct A {virtual void foo(){}};
struct B {virtual void foo(){}};
int main() {
A *a = new A();
B *b = new B();
A *aPtr1 = dynamic_cast<A*>(b);
cout << (aPtr1 == 0) << endl; // Prints 1
A *aPtr2 = dynamic_cast<A*>(a);
cout << (aPtr2 == 0) << endl; // Prints 0
delete a;
delete b;
return 0;
}
The first dynamic_cast
fails, because b
points to an object of a type incompatible with A*
; the second dynamic_cast
succeeds.
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