Bugster
Bugster

Reputation: 1594

C++ call a child's method from a vector of parents?

Say that you have the following class:

class Parent
{
   // methods and members go here
};

then you create a child based on the parent:

class Child : public Parent
{
   public:
      someFunction();
};

Now class Parent doesn't have someFunction() but class Child does. Say that you have a vector of Parent classes, and you want to call the child's method, assuming that the vector holds instances of parents and children, given that they're both the same base type.

std::vector<Parent> myContainer;
myContainer.push_back(a parent);
myContainer.push_back(a child);

myContainer[1].someFunction();

How can I make this work? I'm basically trying to create a vector of parents, but children also go in that vector. I want to call a method that's exclusive for children. Is that possible?

Upvotes: 5

Views: 3596

Answers (3)

Acha Bill
Acha Bill

Reputation: 1255

class Parent
{
    virtual void foo(){}    //dummy function to make Parent polymorphic
};
class Child : virtual public Parent
{
public:
    void about()
    {
        cout << "Child" << endl;
    }
};
int main()
{

    vector<Parent*> vec;
    vec.push_back(new Parent());
    vec.push_back(new Child());

    for (int i = 0; i < vec.size(); i++)
    {
        Child *child = dynamic_cast<Child*>(vec.at(i));
        if (child)
            child->about();     
    }

    return 0;
}

Upvotes: 4

David Schwartz
David Schwartz

Reputation: 182865

You create a vector of Parent objects. There's no polymorphism here. Vectors contain values. If you want a polymorphic container, you have to use something else.

It's just as if you did

Parent myObject;

No matter what you do to myObject later, it will still be a Parent. Even if you do myObject = Child().

Upvotes: 1

ivanw
ivanw

Reputation: 511

Polymorphism only works with pointers and references, so if you create a vector of pointers, then it is possible.

Upvotes: 7

Related Questions