Accessing derived class members with a base class pointer

Posted by LRB on Stack Overflow See other posts from Stack Overflow or by LRB
Published on 2010-05-06T23:56:17Z Indexed on 2010/05/06 23:58 UTC
Read the original article Hit count: 168

Filed under:

I am making a simple console game in C++

I would like to know if I can access members from the 'entPlayer' class while using a pointer that is 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:
    entPlayer() {

        Name = "";
        Id = 0;

    }

    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 would I be able to call ply->setName etc?

OR

If it's not possible that way, what would be a better way?

© Stack Overflow or respective owner

Related posts about c++