Reputation: 170
I have a std::vector of pointers of a base class type:
vector<Base*> baseList;
And I push a derived class type onto the vector:
Derived* derivedObject = new Derived();
baseList.push_back(derivedObject);
But when I iterate the list and call the function which is overridden from the base class by the derived class the code in the derived class isn't called. Am I using the vector in the correct way?
My base class has uses the virtual keyword before declaring its functions and the derived class derives the base class with:
class Derived : public Base
Any Idea what I'm doing wrong here?
EDIT:
To call the function I have declared:
typedef vector<App*>::iterator AppIterator;
AppIterator begin() { return l_Apps.begin(); }
AppIterator end() { return l_Apps.end(); }
And I call the function like so:
for (AppIterator it = begin(); it != end(); ++it)
{
(*it)->Initialize();
}
Could the problem be here?
Upvotes: 0
Views: 2981
Reputation: 2992
I tried the thing with iterator... this code works fine for me, so if your problem persists, consider different compiler =)
#include <iostream>
#include <vector>
class Base
{
public:
virtual void f()
{
std::cout << "Base\n";
}
};
class Derived: public Base
{
public:
virtual void f()
{
std::cout << "Derived\n";
}
};
int main()
{
std::vector<Base*> s;
s.push_back(new Base());
s.push_back(new Derived());
s.push_back(new Base());
s.push_back(new Derived());
s.push_back(new Base());
s.push_back(new Derived());
for (std::vector<Base*>::iterator it = s.begin(); it != s.end(); ++it)
{
(*it)->f();
}
return 0;
}
the output I have:
Base
Derived
Base
Derived
Base
Derived
also you might try to cast the pointers by dynamic_cast<>
, even though it defeats the whole point of using virtual methods. Good luck.
Upvotes: 1