Suppose I have class A
and two derived classes, B
and C
, e.g.:
#include <iostream>
#include <list>
#include <string>
using namespace std;
class A {
public:
virtual void poke() const = 0;
virtual ~A() {};
};
class B : public A {
string _response;
public:
B(const string& response) : _response(response) {}
void poke () const {
cout << _response << endl;
}
};
class C : public A {
string _response;
public:
C(const string& response) : _response(response) {}
void poke () const {
cout << "Well, " << _response << endl;
}
};
Can I somehow initialize an std::list
using the following initializer list: {B("Me"), C("and you")}
, so that polymorphism works when I iterate over the list and call poke()
(i.e., no slicing occurs)? I guess I need to define an std::list<Smth>
, where Smth
accepts temporary objects, has a copy constructor that does move semantics inside (because initialization lists seem to be doing copying and not moving), and supports smart pointers so I can iterate with it
and do (*it)->poke()
. Just for clarity, I want to be be able to write:
list<Smth> test {B("Me"), C("and you")};
for(auto it = test.begin(); it != test.end(); it++) {
(*it)->poke();
}
I was trying to find a simple solution but I got to the point where my program compiled but generated run time errors, and so I gave up at that point... Maybe somehow make a unique pointer out of a temporary object? Or can I use &&
somehow?