Problem With Inheritance

I may be misunderstanding the concept of inheritance, but I'd like to shove a bunch of derived classes into a list (or array, or vector, or whatever), iterate through that container, and call a common method - as in:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

class parent
{
 int num_gray_hairs;
 public string toString();
}

class child0 : parent
{
 int num_yo_yos;
 ...
 public string toString() {return "yes please\n";}
}

class child1 : parent
{
 char grade_in_calc;
 ...
 public string toString() {return "hello"; }
}

//oh look here's a list

list<parent> list_of_parents; 



//fill it up...

 for (list<parent>::iterator i = list_of_parents.begin(); i != list_of_parents.end(); i++)
 {
  cout<<i->toString();
 }


Maybe the toString() method should be virtual? Maybe the parent should be abstract? Maybe my problem is just that I'm no good with lists?
You declared the list as having type parent. So it has objects of type parent. It knows nothing about derived classes. When you add some object of a derived class to the list the object implicitly converted to the type parent that is all data that constitute the derived class are ignored.
To get the effect of the polimorphism you could define the list as std::list<parent *> and define function toString with function specifier virtual.
Topic archived. No new replies allowed.