Vector Problem

Started by
3 comments, last by Halsafar 18 years, 1 month ago
Say I have a class called "ClassA", and I have two more classes which subclass "ClassA" called "ClassB" and "ClassC". If I create a vector:


vector<ClassA> someObjects;


And then I use this vector to add objects of type "ClassB" and "ClassC". If I call a method from one of the objects in the vector how I make sure it calls the overwritten method in either "ClassB" or "ClassC" rather than calling the original in "ClassA".... Hope that makes sense.
Advertisement
If you want to store multiple object types in a vector, you'll need to store (smart) pointers to the base class. You can't store them by value. This leads to a problem called slicing: where only the base class parts of an object are copied.
does this mean that in each vector have 2 pointers, 1 for class b and another for class c? so if you want to call class c function, use class c pointer.


Quote:Original post by SiCrane
If you want to store multiple object types in a vector, you'll need to store (smart) pointers to the base class. You can't store them by value. This leads to a problem called slicing: where only the base class parts of an object are copied.


Quote:Original post by baker
does this mean that in each vector have 2 pointers, 1 for class b and another for class c? so if you want to call class c function, use class c pointer.

No, just have a single ClassA pointer. So long as you only use virtual functions defined in ClassA, everything will work itself out when you actually go to use the pointer.

CM
class A
{
public:
virtual void foo() = 0;
}

class B : public A
{
public:
void foo() {cout << "B Hello" << endl;}
}

int main()
{
vector<A*> v;
B b1;

v.add(&b1);
v[0]->foo();
}

This topic is closed to new replies.

Advertisement