Reference code:
#include <vector>
#include <iostream>
class Func {
public:
virtual void call() {
std::cout<< "Func -> call()" << std::endl;
}
};
class Foo : public Func {
public:
void call() {
std::cout<< "Foo -> call()" << std::endl;
}
};
class Bar : public Func {
public:
void call() {
std::cout<< "Bar -> call()" << std::endl;
}
};
int main(int argc, char** argv) {
std::vector<Func> functors;
functors.push_back( Func() );
functors.push_back( Foo() );
functors.push_back( Bar() );
std::vector<Func>::iterator iter;
for (iter = functors.begin(); iter != functors.end(); ++iter)
(*iter).call();
}
When run that code, it produces the following output on my computer:
$ ./test
Func -> call()
Func -> call()
Func -> call()
Would there be any way to ensure that the correct virtual function is called in this instance? I'm new at C++ but my best guess is that here:
(*iter).call();
It's being cast to a Func
object. Is this correct?