C ++ Polymorphism and Slicing

The following code displays

Derived
Base
Base

But I need each Derived object to fit in User :: objects, call its own print function, but not the base class. Can I achieve this without using pointers? If this is not possible, how can I write a function that deletes User :: items one by one and frees up memory so that there are no memory leaks?

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Base{
public:
  virtual void print(){ cout << "Base" << endl;}
};

class Derived: public Base{
public:
  void print(){ cout << "Derived" << endl;}
};

class User{
public:
  vector<Base> items;
  void add_item( Base& item ){
    item.print();
    items.push_back( item );
    items.back().print();
  }
};

void fill_items( User& u ){
  Derived d;
  u.add_item( d );
}

int main(){
  User u;
  fill_items( u );
  u.items[0].print();
}
+3
source share
3 answers

You need to use pointers, and you need to give your base class a virtual destructor. A destructor must not do anything, but it must exist. Your add function is as follows:

void add_item( Base * item ){
    item->print();
    items.push_back( item );
}

- vector<Base *>. ( ):

for( int i = 0; i < items.size(); i++ ) {
    delete items[i];
}
items.clear();
+5

, , Derived delete Base.

class Base{
public:
  virtual void print(){ cout << "Base" << endl;}

  virtual ~Base( ) { }  // virtual destructor
};

Boosts ptr_vector , .

+1

:

, , Base abstract (, pure virtual). , . , : Base , push_back (). . Derived Base.

0
source

Source: https://habr.com/ru/post/1739772/


All Articles