I am new to C++ as I made the switch from Java/C#. Can somebody explain why my code doesn't work like I think it should. I have a simple hierarchy of Animal class which is then inherited by Dog and Cat. The only difference between the classes is their virtual method toString() /which obviously returns a string based on which of the classes it is called on/. Okay so I am inputting information and creating the classes with cin and pushing them into a vector of Animals. However when I tried to call their toString() I got the result from the base toString() and not the overriden one. Here is the code at this point:
#include <iostream>
#include <vector>
#include "animal.h"
#include "cat.h"
#include "dog.h"
using namespace std;
int main()
{
vector<Animal> animals;
string type;
string name;
int age;
int weight;
while(cin >> type){
cin >> name >> age >> weight;
if(type == "dog"){
animals.push_back(Dog(name, age, weight);
}
else {
animals.push_back(Cat(name, age, weight);
}
}
for(vector<Animal>::iterator iter = animals.begin(); iter != animals.end();
iter++){
cout << iter -> toString() << endl;
}
return 0;
}
But then after I did some googling I found a suggestion that I should use pointers because of something called object slicing. So then my code turned into this:
#include <iostream>
#include <vector>
#include "animal.h"
#include "cat.h"
#include "dog.h"
using namespace std;
int main()
{
vector<Animal*> animals;
string type;
string name;
int age;
int weight;
while(cin >> type){
cin >> name >> age >> weight;
if(type == "dog"){
Dog tempDog(name, age, weight);
animals.push_back(&tempDog);
}
else {
Cat tempCat(name, age, weight);
animals.push_back(&tempCat);
}
}
for(vector<Animal*>::iterator iter = animals.begin(); iter != animals.end();
iter++){
cout << iter -> toString() << endl;
}
return 0;
}
And now I am getting a compiler error suggesting I should use '->';
Also a side question while I am here I would like to ask. Is there a way of overriding a virtual method from the .cpp file and not the header file where the class is defined. I am recently getting into the oop in c++ and to my idea is that in the header file I just define prototypes of the members of the class and I do the implementation in a different .cpp file.