Reputation: 721
I have a base class and several inherited classes.
class Base {
public:
void update();
};
class Inherited1 {
public:
void update(); // override base method
};
class Inherited2 {
public:
void update(); // override base method
};
I have a vector of the base class containing pointers to several instances of the subclasses, i.e.
vector<Base> myObjects;
Base *i1 = new Inherited1();
Base *i2 = new Inherited2();
myObjects.push_back(*i1);
myObjects.push_back(*i2);
I want to be able to go through each element in the vector and automatically call the subclass (i.e. overriden) methods, like:
for (int i=0; i<myObjects.size(); i++) {
(*myObjects[i]).update();
}
But this doesn't work -- it just calls the superclass method. What is the proper way to achieve this?
Upvotes: 1
Views: 586
Reputation: 48
#include <iostream>
#include <vector>
using namespace std;
class Base{
public:
virtual void update(){
cout << "base" << endl;
}
};
class Inherited1: public Base {
public:
void update(){
cout << "Inherited1" << endl;
}
};
class Inherited2: public Base {
public:
void update(){
cout << "Inherited2" << endl;
}
};
int main()
{
vector<Base*> myObjects;
Base *i1 = new Inherited1();
Base *i2 = new Inherited2();
myObjects.push_back(i1);
myObjects.push_back(i2);
for (auto iter = myObjects.begin(); iter != myObjects.end(); ++iter)
{
(*iter)->update();
}
}
the output is
Inherited1
Inherited2
Upvotes: 1
Reputation: 310910
The code snippets shall not be compiled. This
vector<Base> myObjects;
is not a vector of pointers to objects of the base class. It is a vector of objects of the base class.
You need to define the vector as
vector<Base *> myObjects;
As for function update then it must be defined as virtual in the base class
virtual void update();
Only in this case there will be a polymorphic hierarchy of classes.
I think there is a typo in the defining of the derived classes. There should be
class Inherited1 : public Base
instead of
class Inherited1
Upvotes: 4
Reputation: 3806
You must declare public inheritance, and then, declare memvbers as virtual
class Base {
public:
virtual void update();
};
class Inherited1: public Base{
public:
virtual void update(); // override base method
};
class Inherited2: public Base{
public:
virtual void update(); // override base method
};
Upvotes: 4
Reputation: 23793
Your design is almost good, but you need to declare update() virtual in the Base class (and if using C++11, you may mark the overriding method with the new 'override' keyword).
Without the "virtual" keyword, polymorphism wont take place (you are simply redeclaring and hiding "update" in each subclass)
Upvotes: 1