What is a possible workaround for object slicing in c++?

后端 未结 3 1983
情书的邮戳
情书的邮戳 2020-12-06 03:12

This is the code:

#include 
#include 
#include 
using namespace std;
class A {
public:
  virtual const string f()         


        
相关标签:
3条回答
  • 2020-12-06 03:20

    You need to store pointers. If these refer to dynamically allocated objects, use smart pointers.

    0 讨论(0)
  • Ordered from most simple, to most complex (but most nice).

    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 don't want slicing to happen, you need to take into account the fact that different objects may have different sizes -- ergo you need a solution that can work with variable sizes -- that makes storing on the heap a must.

    0 讨论(0)
  • 2020-12-06 03:38

    Well, in your code you could use a vector of B. Note that virtual functions will only be dispatched properly if called via a pointer or a reference. However, assuming you really want your vector to contain both A and B objects, you need to make it vector of A pointers, and create the A and B objects dynamically.

    0 讨论(0)
提交回复
热议问题