It is ordered from the simplest to the most complex (but the most pleasant).
Solution 1:
vector<B> v; v.push_back(B()); cout << v.at(0).f() << endl;
Solution 2:
vector<A*> v; v.push_back(new B()); cout << v.at(0)->f() << endl; while(!v.empty()) { delete v.back(); v.pop_back(); }
Solution 3:
vector<boost::shared_ptr<A>> v; v.push_back(boost::make_shared<B>()); cout << v.at(0)->f() << endl;
If you do not want the slicing to happen, you need to consider the fact that different objects can have different sizes - you need a solution that can work with variable sizes - this makes storage on the heap necessary.
Kornel kisielewicz
source share