Note: This is almost a duplicate of this entry: Abstract classes and Pointers
I need to create a vector of virtual classes. Here the idea:
#include <vector>
using namespace std;
class VirtualFoo {
protected:
VirtualFoo();
virtual ~VirtualFoo();
public:
virtual void doStuff()=0;
};
class ConcreteFoo: public VirtualFoo {
public:
ConcreteFoo(double a);
virtual ~ConcreteFoo();
void doStuff();
private:
double a;
};
class Foo {
public:
Foo(std::vector<VirtualFoo> foos);
virtual ~Foo();
void doAllStuff();
protected:
std::vector<VirtualFoo> foos;
};
And I would like to use it this way:
int main(int argc, char *argv[]){
std::vector<ConcreteFoo> cfoos;
cfoos.push_back(ConcreteFoo(1.0));
cfoos.push_back(ConcreteFoo(2.0));
Foo foo = Foo(cfoos);
foo.doAllStuff();
}
Of course this does not work because cfoos is a vector of VirtualFoo and not ConcreteFoo.
Now, if I do not use a vector of VirtualFoo but a vector of VirtualFoo* and push back pointers to instances of ConcreteFoo, that seems to work fine.
Just, I am not sure it is the cleanest way to go. It's more like I did not think of any other way of doing this. Is doing this ok ?