Search code examples
c++oopvariablesencapsulation

Edit variables inherited from parent class


I have this code for a basic entity system I'm testing

Enity.h

class Enemy
{
    public:
    void attack(Player player);
    virtual void die();

    protected:  //Info variables
    int attackDamage;
    std::string name;
    bool alive;
}

class ChildEnemy1 : public Enemy
{
    name = "Enemy1" //Invalid
};

class ChildEnemy2 : public Enemy
{
    name = "Enemy2" // Invalid
};

How would you change the Info variables (attackDamage, name, alive) without inheriting a public setter function (retain encapsulation).

EDIT: This is not a duplicate question as I have not found an adequate answer to this problem on SO


Solution

  • Initialize the members in the constructor.

    class ChildEnemy1 : public Enemy
    {
        ChildEnemy1() : name("Enemy1") {}
    };