chris chris - 1 month ago 16
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 ();
t->color="white";
t->tonnage=32;

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!

EDIT1:

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

EDIT2:

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

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 {
  public:
    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());