0

I have not used C++ in a while, so I'm not sure what the right way is to do what I'm trying to do. I have the following classes:

class A {
public:
   virtual string printStuff() { return "A"; };
};

class B : public A {
public:
   string printStuff() { return "B"; };
};

class C : public A {
public:
   string printStuff() { return "C"; };
};

I have an STL vector:

vector<A> vec;

It contains a lot of class A and B objects. When I do:

for (vector<A>::iterator iter = vec.begin(); iter != vec.end(); ++iter) {
   iter->printStuff();
}

All it prints is "A". I would like it to use class B and C's methods.

Thank you.

Squall Leohart
  • 657
  • 2
  • 8
  • 20

1 Answers1

4

A std::vector<A> can only contain objects of type A. If you insert an object of a derived class type, it will be sliced. If you want polymorphic behaviour, use std::vector<A*> (or, better, std::vector<std::unique_ptr<A>>).

Brian Bi
  • 111,498
  • 10
  • 176
  • 312