What is a possible workaround for handling objects in C ++?

This is the code:

#include <string> #include <vector> #include <iostream> using namespace std; class A { public: virtual const string f() const { return "A"; } }; class B : public A { public: const string f() const { return "B"; } }; int main(int ac, char** av) { vector<A> v; v.push_back(B()); cout << v.at(0).f() << endl; return 0; } 

Expected Result: B , but A As I understand it, the splitting of objects occurs. How to avoid this? Should I store pointers in vector instead of object instances? Is this the only choice?

+6
c ++
source share
3 answers

You need to save pointers. If they relate to dynamically allocated objects, use smart pointers.

+11
source share

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.

+11
source share

Well, in your code you can use the vector B. Note that virtual functions will only be sent correctly if called through a pointer or link. However, assuming that you really want your vector to contain both objects A and B, you need to make it a pointer vector A and create dynamic objects A and B.

+3
source share

All Articles