chris chris - 1 year ago 84
C++ Question

STL::container, Polymorphism

My OOP knowledge is a bit rusty...
and I try polymorphism 1st time with containers I think.

class car {
public: std::string color;
public: virtual void foo (void) = 0;
public: virtual ~car (void){}


class truck : public car {
public: int tonnage;
public: virtual void foo (void) {}

// expect for subclasses of car


truck *t = new truck ();

std::list <car *> lst; // for any kind of car
lst.push_back (t);

printf ("\n1: %s", typeid (t).name ());
printf ("\n2: %s", typeid (lst.front()).name());

I expected to see

1: P3van
2: P3van

but it was

1: P3van
2: P3car

Is that not possible with containers or whats the problem?
I need to the the subclass out of it, not the parent. As far I read slicing is not the problem with pointers.
Thanks for help!


I added virtual functions. But is is the same result.


I'd like to downcast with the typid-info. Otherwise I can put a id-member into the base-class but I thought it would be possible (e.g. dynamic typecheck/cast).

Answer Source

C++ defines a polymorphic class as a class which has at least one virtual function. typeid doesn't do anything special unless its argument is a polymorphic class. So first, add a virtual destructor to car:

class car {
    virtual ~car() {}
    std::string color;

Also, typeid does not act polymorphically on pointers, only on objects / references. Try

printf ("\n1:    %s", typeid (*t).name ());
printf ("\n2:    %s", typeid (*lst.front()).name());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download