Dean
Dean

Reputation: 517

c++ casting struct pointer to the type value

This may be a stupid question but I'm learning, I'm having trouble with my code:

I'm having problems at this line:

fb->AddEntity(m); // M Needs to be the type Item not Item*

What I need is the object of the value for that type, not the pointer, because I need to pass it to the AddEntity function, How do I cast it?

#include "Handler.h"

FatBoy *fb;

void Entity::Interact()
{
};

void OnNewPacketReceived(BYTE *data, int Length)
{
    switch (data[0])
    {
        case 0x07:
            {
                short length = (short)((data[1] << 8) + data[2]);
                int Index = 0;

                for (int i = 0; i < length; i++)
                {
                    Entity ent;
                    ent.X = (USHORT)((data[Index] << 8) + data[Index + 1]);
                    ent.Y = (USHORT)((data[Index + 2] << 8) + data[Index + 3]);
                    ent.Serial = (UINT)((data[Index + 4] << 24) + (data[Index + 5] << 16) 
                        + (data[Index + 6] << 8) + data[Index + 7]);
                    ent.SpriteID = (USHORT)((data[Index + 8] << 8) + data[Index + 9]);

                    if (ent.SpriteID > 0x8000 && ent.SpriteID < 0x9000)
                    {
                        Item *m = dynamic_cast<Item*>(&ent); 
                        m->UNKNOWN1 = 0x00;
                        m->UNKNWON2 = 0x0000;
                        m->Interact();

                        fb->AddEntity(m); // M Needs to be the type Item not Item*
                    }
                    else
                    {
                        Monster *m = dynamic_cast<Monster*>(&ent); 
                        m->UNKNOWN = 0x00000000;
                    }
                }
            } break;
        default: break; 
    }
}

void FatBoy::AddEntity(Entity ent)
{
    this->Entities.push_back(ent);
}

Upvotes: 1

Views: 136

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283624

To get the object from a pointer, use the dereference operator *.

So you would say

fb->AddEntity(*m);

In fact, every time you use m->member, that is exactly the same as (*m).member.

On the other hand, AddEntity should probably not be passing by value (it makes unnecessary copies). Consider

void FatBoy::AddEntity(const Entity& ent)

instead.

Upvotes: 5

simonc
simonc

Reputation: 42165

Use *m if you have a pointer and want to pass by value or by reference

fb->AddEntity(*m);

Upvotes: 5

Related Questions