vendredi 10 juin 2016

upcasting variable in derived class c++


How to change the type of a inherited variable in the derived class? I have the following classes:

class Position;
class StonePosition;

class Position {
public:
    Position() {}
};

class StonePosition : public Position {
    int count;
public:
    StonePosition(const int count) { this->count = count; }
    int getCount() { return this->count; }
    void setCount(int count) { this->count = count; }
    friend ostream& operator<<(ostream&, StonePosition);
};

class Board {
protected:
    Position* crrPos;
public:
    Board() { }
    Position* getCrrPos() { return crrPos; }
    void setCrrPos(Position* pos) { crrPos=pos; }
};

class StoneBoard : public Board {
public:
    StoneBoard(const int &count) { this->crrPos=new StonePosition(count); } //<----------------
    StonePosition* getCrrPos() { return (StonePosition*)crrPos; }
    void setCrrPos(StonePosition* pos) { crrPos=pos; }
};

Place in which the problem is marked by an arrow. I need to change the type of a variable from Position to StonePosition in the StoneBoard class. I found an option that can be used upcasting, but it works only within a single method, and I need to change the variable for the entire class.


Aucun commentaire:

Enregistrer un commentaire