Search code examples
c++classderived-class

How to set BaseClass variable from DerivedClass parameter


I have the classes Player and HumanPlayer. HumanPlayer is derived from Player.

class Player {
private:
    int id;
protected:
    string name;
public:
    Player(int id);
    ~Player();
}

class HumanPlayer : public Player {
public:
    HumanPlayer(int id, string name);
}

I want to make a constructor for HumanPlayer the set the Player id and name but I don't seem to figure out how to set Player::id to the HumanPlayer::id.

This is what I have worked out but gives an error "int Player::id' is private within this context"

HumanPlayer::HumanPlayer(int id, string name) : Player(id){
    this -> id = id;
    this -> name = name;
}

Solution

  • For your understanding.

    class Player {
    private:
        int id;
    protected:
        std::string name;
    public:
    
        //Base class constructor, initialize Id.
        Player(int i):id(i)
        {}
    
        ~Player() {}
    
        //Test
        int GetId()
        {
            return id;
        }
    
        std::string GetName()
        {
            return name;
        }
    };
    
    class HumanPlayer : public Player {
    public:
        HumanPlayer(int i, std::string s) :Player(i) //Pass on Id  base class constructor
        {
            name = s; //Protected variable accessible.
        }
    };
    
    void main()
    {
        HumanPlayer hPlayer(10, "Test");
    
        std::cout << hPlayer.GetId() << std::endl;
        std::cout << hPlayer.GetName() << std::endl;
    }