Access to members of a derived class with a base class pointer

I am making a simple console game in C ++

I would like to know if I can access the elements from the entPlayer class using a pointer pointing to the base class ("Entity"):

class Entity {
public:
    void setId(int id) { Id = id; }
    int getId() { return Id; }
protected:
    int Id;
};

class entPlayer : public Entity {
    string Name;
public:
    void setName(string name) { Name = name; }
    string getName() { return Name; }
};

Entity *createEntity(string Type) {
    Entity *Ent = NULL;
    if (Type == "player") {
        Ent = new entPlayer;
    }
    return Ent;
}

void main() {
    Entity *ply = createEntity("player");
    ply->setName("Test");
    ply->setId(1);

    cout << ply->getName() << endl;
    cout << ply->getId() << endl;

    delete ply;
}

How can I call ply-> setName etc.

OR

If this is not possible, what would be the best way?

+5
source share
4 answers

This is possible with a throw. If you know that the base class pointer points to a derived class object, you can use static_cast:

Entity* e = /* a pointer to an entPlayer object */;
entPlayer* p = static_cast<entPlayer*>(e);
p->setName("Test");

, dynamic_cast , , . , dynamic_cast, . :

Entity* e = /* a pointer to some entity */;
entPlayer* p = dynamic_cast<entPlayer*>(e);
if (p)
{
    p->setName("Test");
}

, , (.. ).

, undefined: , . , .

+11

, - :

public:
void setId(int id) 
{

    Id = id;

}

void virtual setName( string name ) = 0; // Virtual Function 
string virtual getName() = 0; // Virtual Function

int getId() { return Id; }

protected:
    int Id;

};

class entPlayer : public Entity {

    string Name;

public:
    entPlayer() {

        Name = "";
        Id = 0;

    }

    void entPlayer::setName(string name) {  // Must define function

        Name = name;
}

string entPlayer::getName() { return Name; } // again must define function here

};
+1

:

entPlayer * pPlayer = dynamic_cast<entPlayer *>(pointer_to_base);

( ) .

NULL.

0

++ , , , , , , - . , (RTTI), dynamic_cast.

Not knowing your broader context, it is hard to say what you should do instead. I can say that if you need a more specific pointer, you should put a ring on it , you almost certainly should not use a function that returns Entity*, and there is probably a better approach.

0
source

All Articles