Bren
Bren

Reputation: 3706

Calling virtual methods of unknown child class

I have the following set up:

class Parent {
    virtual void foo(int x) = 0;
};
class Son : public Parent {
    void foo(int x) {};
};
class Daughter : public Parent {
    virtual void foo(int x) {};
};

If I have vector<Parent> parents and I am going though the vector with a loop as seen here:

for (int i = 0; i < parents.size(); i++) {
    Parent s = parents[i];
    s.foo(-1);  
}

How do I call the children' foos (they could be Sons or Daughters)? I am getting two errors currently:

  1. Variable type 'Parent' is an abstract
  2. Variable type 'Parent' is an abstract class

Upvotes: 1

Views: 138

Answers (1)

Christophe
Christophe

Reputation: 73542

First, you have to make Son and Daughter be derived classes of Parent:

class Son : public Parent {
    ...
};
class Daughter : public Parent {
    ...
};

Then, to have a vector of polymorphic objects, you can't store the objects therein. You have to take a vector of pointers to objects for polymorphism to work.

vector<Parent*> parents;

or better:

vector<shared_ptr<Parent>> parents;

Why?

  • No Parent object can be instantiated because it's an abstract class. You can only create derived classes of it.
  • if Parent was not abstract, your code could work, but by putting a Son or a Daughter in the vector, it would be sliced.

Upvotes: 1

Related Questions