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.