0

Lets say I have an Entity class with the variable x and it is defined as 0 in that class.

Well then I make a derived class Player but I want the Player's inherited x by default to be 1 and not 0, so that every Player I create has x be 1 by default.

Is this possible?

And if it is, how can I do it?

anastaciu
  • 23,467
  • 7
  • 28
  • 53
Aravash
  • 39
  • 3

2 Answers2

2

Yes it's possible, I've read the comments and I gather you want the base member to be private, one option is to inherit base class constructor.

Classes Sample 1

class Entity{
private:
    int x;
public:
    Entity(int i = 0) : x(i) {} //initialize x to 0
    int getX() {return x;}
};

class Player: public Entity{
public:
    Player() : Entity(1) {}   //inherit base class constructor initializing x to 1
};

This implementation has a potential weakness, it allows for the construction of objects initializing x. If you do not want this you can have a protected constructor that allows derived classes to specify the member value, preventing the construction of objects that can initialize x.

Classes Sample 2

class Entity {    
    int x = 0;    
public:
    Entity() = default; //default construtor
    int getX(){return x;}

protected:
    Entity(int i) : x(i) {} //protected constructor, 
};

class Player : public Entity {
public:
    Player() : Entity(1) {}
};

Usage

#include <iostream>

using std::cout;
using std::endl;

int main()
{   
    Entity e;
    cout << e.getX() << endl;

    Player p;
    cout << p.getX();

    return 0;
}

Deppending on the compexity of your classes you might also make the protected construtor explicit

Output

0
1

Note that this is a very simplified version, you should observe the rules of class construction like for instance The rule of three/five/zero.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
1
class Entity {
  private:
    int x;
  public:
    Entity() : x(0)
  {}
    void set_x(int y){
      x = y;
    }
    int get_x(){
      return x;
    }

};

class Player : public Entity {
  public:
    Player() 
    {
      set_x(1);
    }
};
  • what is the point of "player()" under public? can I not simply do x=1 in the player class without it being within that? – Aravash Apr 20 '20 at 19:52
  • @user4581301 There can be lots of corner cases, and I think a general design is OK for the author of this question. – Hamed Norouzi Apr 20 '20 at 19:59
  • @Aravash I don't think so. The assignment should take place when the construction of the Player class happens. – Hamed Norouzi Apr 20 '20 at 20:03