Reputation: 3706
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:
Variable type 'Parent' is an abstract
Variable type 'Parent' is an abstract class
Upvotes: 1
Views: 138
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?
Upvotes: 1