I've created a BaseClass
and two subclasses: SubOne
and SubTwo
. After that I created a collection called MyCollection
which stores the instances in a vector.
Both the base class, and the subclasses have the method getString
. Base class returns with base
, and the subclasses with sub1
and sub2
.
I don't get any warning or error during the compilation. But for some reason, if I try to iterate over the vector, the subclasses return "base"
#include <iostream>
#include <vector>
class BaseClass {
public:
BaseClass() {}
std::string getString() {
return "base";
}
};
class SubOne : public BaseClass {
public:
SubOne() : BaseClass() {}
std::string getString() {
return "sub1";
}
};
class SubTwo : public BaseClass {
public:
SubTwo() : BaseClass() {}
std::string getString() {
return "sub2";
}
};
class MyCollection {
private:
std::vector<BaseClass> instances;
public:
MyCollection() {}
void add(BaseClass & ins) {
instances.push_back(ins);
}
std::string printString() {
for(std::vector<BaseClass>::iterator it = instances.begin() ; it != instances.end(); ++it) {
std::cout << it->getString() << std::endl;
}
}
};
int main() {
MyCollection *coll = new MyCollection();
SubOne* s1 = new SubOne();
SubTwo* s2 = new SubTwo();
coll->add(*s1);
coll->add(*s2);
coll->printString();
return 0;
}