I want to create an array of pointers which are animal types, but I'm not sure if I did it correctly. Most likely, I didn't. Another question is that I want to return the animal type instead of Animal[rand] in line 38-40. What can I do ?
I got what you mean, but I don't get how I can use them.
I try "cout<<Animal[0]->Name()<<endl;" But it didn't return me the name "Cow"...
And I didn't get the part that use the selected animal’s characteristic methods to display its characteristics.
Here is what I wrote for the class cow and class animal
Although Animal::Animal(string name) takes a string as an argument, you're not actually assigning it to the data member _name. Thus, when you call Animal[0]->Name(), the string it returns is empty.
As for the second problem - if you want to use a base class pointer to access the overriden versions of methods in derived classes, you need to declare those methods to be virtual in the base class.
Thanks! After I make all characteristic methods virtual, what should I do in order to make something like Animal[0].IsMammal=true I want to access the derived base class by the array like Animal[0].IsMammal instead of Cow.IsMammal.
You should make the "IsMammal" and other properties, a property of Animal, and not a property of Cow. Remember to make it public, or to give IsMammal and SetMammal functions.
I think the problem is that you're trying to write Object Oriented code without understanding Object Oriented Design. We all have to start somewhere, so don't feel bad about it.
Can I point out that lines 11 - 13 in main are errors - you cannot have a variable name being the same as a class name. Did those errors not show up as compile errors?
Maybe I should downgrade my comment a lot, and say that it is bad practice / confusing.
Having the object name being the same could lead newbies into directly referring to private variables.
I name my classes with a leading C, as in CCow, CHorse, CDog - then I can have objects Cow, Horse, Dog if I wanted, without too much confusion - although I would probably have named the objects something else.
Thank You a lot ! I finished this part.
I have two more questions.
The 1st question is that I want the player start the game by pressing enter and end the game by entering "no", but I fail! The game doesn't start by just pressing enter...what should I do to fix it ?
1 2 3 4 5 6 7 8 9 10
bool playthegame=true;
cout<<"You wnat to play the game ? )";
char choice;
cin>>choice;
if (choice=="No"||choice=="No"||choice=="NO"||choice=="nO"||choice=="n"||choice=="N")
playthegame=false;
elseif (choice=="a")
playthegame=true;
while (playthegame==true)
{....}