I don't think I am allowed to initialize type {0} inside the class |
Why not? That is valid modern C++. If you are learning C++, then you should learn modern C++ (although there is job market for legacy code maintainers too).
I presume the goal is:
1 2 3 4
|
int main() {
Creature jack;
// Assert: jack.type==0, jack.strength==10, jack.hitpoints==10
}
|
That has nothing to do with the getSpecies. The getSpecies does take a parameter that has name '
type
', but that is not the member '
type
' of every Creature. Same name re-used in different context.
A problem with that function is that we cannot:
cout << jack.getSpecies();
We cannot get the string representation of the type of an existing Creature object. We have to:
cout << jack.getSpecies( 42 );
In other words, we would have to get the type of jack and then call the function with the type as argument (except that it is a private member).
What the function does is to convert a numeric value into text. A mapping. A lookup.
It could be a standalone function:
1 2 3 4 5
|
string getSpecies(int type);
int main() {
cout << getSpecies( 42 );
}
|
It could be a static member:
1 2 3 4 5 6 7 8
|
class Creature {
public:
static string getSpecies(int type);
};
int main() {
cout << Creature::getSpecies( 42 ); // We don't need any creatures in order to test whether 0 is "Human"
}
|
Having both 'type' and 'creature' member variables is redundant, i.e. waste of memory, since we can always call getSpecies to convert type to text.
Finally:
1 2 3 4
|
Creature::Creature()
{
strength = 10; // this is assignment, not initialization
}
|
1 2 3 4 5
|
Creature::Creature()
: strength{10} // this is initialization
{
// nothing to do here
}
|