+ 1
Why do I can't initialize protected variable through constructors aren't they inherited protected members of derived class?
class Enemy { protected: int attackPower; public: void setAttackPower(int a){ attackPower = a; } }; class Ninja: public Enemy { public: Ninja(int a) : attackPower(a){} void attack() { cout << "Ninja! - "<<attackPower<<endl; } }; class Monster: public Enemy { public: Monster(int a) :attackPower(a){} void attack() { cout << "Monster! - "<<attackPower<<endl; } }; the error is saying class 'Ninja' does not have any field attackPower. doesn't attackPower is the inherited protected member of class Ninja.
1 Antwort
+ 2
Hi,
this doesn't work when using an initialization list. If you do it in the constructor's body, it should work. For a full explanation to this very problem, see http://stackoverflow.com/questions/2290733/initialize-parents-protected-members-with-initialization-list-c
Regards,
Alex