Hallo
I am new to c++ and learning this Lists and Iterators from quite a few days.
I am stuck and confused now.
First what I got to know abouts Lists and Iterators were
Lists ist just like a normal list in which you can push your objects or values(strings, int and so on) like we do in stack
Iterators are just to poitn out the stuff we pushed in and we can also know what we pushed up just by dereferecing it.
Now my question is Why some people put a pointer with a datatype sometimes. For eg
std::list<animals*> animal_list; // where animal is my class
std::list<animals*> ::iterator iter; //
We do this to access the pointers to the class animals for eg I tried making this code
#include <stdio.h>
#include <iostream>
#include <list>
#include <string>
using namespace std;
class Animals
{
public:
void getName(){
cout << "this is a"<< *it;
}
};
class Dog : public Animals{
public:
Dog(string dog){
cout << "the breed of the dog is"<< dog<< endl ;
}
};
class Cat : public Animals{
public:
Cat(string colour){
cout << "the color of the cst is"<<colour<<endl;
}
};
class Rabbit : public Animals{
public:
Rabbit(string colour){
cout << "the color of the rabbit is"<< colour<<endl;
}
};
int main()
{
list<animals*> animals;
Dog *d = new Dog("labrador");
Cat *c = new Cat("braun");
Rabbit *r = new Rabbit("black n white");
animals.push_back(d);
animals.push_back(c);
animals.push_back(r);
list<animals*>::iterator it;
for (it = animals.begin(); it != animals.end(); ++it){
cout << (*it)->getName(); }
}
In this case I made 3 derived classes and all these are inheriting animals class. My main purpose is to access the function getName() declared in base class.
Now I made three pointers pointing to these classes. And then I pushed them up in the list in order to have the dog, cat and rabbit in my list. I don't know if I'm right or wrong.
I am really screwed up.Its not getting in my head.
Please help and sorry for such a lng description. I just wanted to clearly explain myself
Thanks
P.s : Please don't get confuse after reading it.