The title may be a little confusing but hear me out. I have this two classes , Entity and Human. Entity is the parent class of human. When I create a human object, it will require an Entity object passed as argument in the constructor so all the human objects that I create has the same Entity object info.
This is my problem: If I change some data from the Entity object I want to update all the data from the Human objects that I created using that Entity Object in the constructor.
I want to implement this in ones of my University projects so I am allowed to use only the standard library. I wrote this example so it's easier to understand:
#include <iostream>
using namespace std;
class Entity{
private:
//DATA
int life;
public:
//DEFAULT CONSTRUCTOR
Entity() {life = 100;}
//PARAMETRIZED CONSTRUCTOR
Entity(int life) {this -> life = life;}
//GETTER
int get_life(){return life;}
//SETTER
void set_life(int new_life){life = new_life;}
//FUNCTIONS
void print_life() {cout << "This entity has " << life << " life" << endl;}
};
class Human : public Entity{
public:
//DATA
string name;
//DEFAULT CONSTRUCTOR
Human() {name = "N/A";}
//PARAMETRIZED CONSTRUCTOR
Human(string name, Entity object){
Entity::set_life(object.get_life());
this -> name = name;
}
};
int main(){
//DATA
Entity Human_data(50);
Human Hero("Steve", Human_data);
Human Villain("Mike", Human_data);
//BODY
Human_data.set_life(5000);
Hero.print_life();
//END MAIN
return 0;}
As you can see, after I update Human data life from 50 to 5000, it does not also change Hero and Villain life to 5000 and only changes Human data life to 5000.
Entityobject inside theHumanobject?Human_dataobject is wrong, and instead you should just pass thelifevalue itself to theHumanconstructor, for passing on to theEntityconstructor (in aconstructor initializer list). Then just callHero.set_life(5000)instead. What problem is supposed to be solved by having yourEntityobject separate and passed to the construction of theHumanobject?