Aravash
Aravash

Reputation: 39

Initializing a member in an inherited class with different value of base class

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?

Upvotes: 0

Views: 1302

Answers (2)

anastaciu
anastaciu

Reputation: 23832

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.

Upvotes: 2

Hamed Norouzi
Hamed Norouzi

Reputation: 71

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);
    }
};

Upvotes: 1

Related Questions