Sign in to follow this  

Vector Problem

This topic is 4308 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.


Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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();
}

Share this post


Link to post
Share on other sites

This topic is 4308 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this