Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ to c#'s "As"?

Tags:

c++

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[];
};
like image 838
Dean Avatar asked Feb 19 '23 02:02

Dean


1 Answers

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.

like image 200
Sergey Kalinichenko Avatar answered Feb 27 '23 08:02

Sergey Kalinichenko