Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ polymorphism and slicing

The following code, prints out

Derived
Base
Base

But I need every Derived object put into User::items, call its own print function, but not the base class one. Can I achieve that without using pointers? If it is not possible, how should I write the function that deletes User::items one by one and frees memory, so that there should not be any 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();
}
like image 484
Draco Ater Avatar asked Feb 20 '26 05:02

Draco Ater


2 Answers

You need to use pointers, and you need to give your base class a virtual destructor. The destructor does not have to do anything, but it must exist. Your add function then looks like:

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

where items is a vector<Base *>. To destroy the items (assuming a virtual destructor):

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

You need a virtual destructor for base to make sure objects of type Derived get destroyed properly when calling delete on a pointer of type Base.

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

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

Then you can use Boosts ptr_vector to store pointers to your objects that get deleted when the container gets destroyed.

like image 26
Björn Pollex Avatar answered Feb 21 '26 18:02

Björn Pollex