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();
}