'Getting a syntax error when trying to use a protected variable in a derived class
I have a class named Creature with 3 protected variables: string name, int quantity and string type. I have two derived classes Phoenix and Basilisk.
I tried redefining some of the variables inside each derived class, so that it becomes that value for that derived class only, but I get these errors for each line I try redefine a variable.
Error C2059 syntax error: '='
Error C2238 unexpected token(s) preceding ';'
class Creature {
protected:
string name;
int quantity;
string type;
};
class Phoenix : public Creature {
Creature::type = "phoenix";
};
class Basilisk : public Creature {
Creature::type = "basilisk";
Creature::quantity = 1;
};
Solution 1:[1]
THis is not valid c++
class Phoenix : public Creature {
Creature::type = "phoenix";
};
you need
class Creature {
protected:
string name;
int quantity;
string type;
Creature(string t) :type(t) {}
};
class Phoenix : public Creature {
Phoenix() :Creature("phoenix") {};
};
NOTE: storing a type in a class heirarchy is considered a c++ code smell. Better to use behavior than to ask for a type. If its for display purposes then the canonical thing to do it to have a method called something like 'creatureType' thats implemented by the derived classes that returns a string.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pm100 |
