+ 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.

23rd Dec 2016, 6:07 PM
Abhishek Sharma
Abhishek Sharma - avatar
1 Odpowiedź
+ 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
23rd Dec 2016, 8:40 PM
alex189