Can I Have Polymorphic Containers With Value Semantics in C++11?
Posted
by
John Dibling
on Stack Overflow
See other posts from Stack Overflow
or by John Dibling
Published on 2010-09-10T19:45:51Z
Indexed on
2012/09/29
3:38 UTC
Read the original article
Hit count: 144
This is a sequel to a related post which asked the eternal question:
Can I have polymorphic containers with value semantics in C++?
The question was asked slightly incorrectly. It should have been more like:
Can I have STL containers of a base type stored by-value in which the elements exhibit polymorphic behavior?
If you are asking the question in terms of C++, the answer is "no." At some point, you will slice objects stored by-value.
Now I ask the question again, but strictly in terms of C++11. With the changes to the language and the standard libraries, is it now possible to store polymorphic objects by value in an STL container?
I'm well aware of the possibility of storing a smart pointer to the base class in the container -- this is not what I'm looking for, as I'm trying to construct objects on the stack without using new
.
Consider if you will (from the linked post) as basic C++ example:
#include <iostream>
using namespace std;
class Parent
{
public:
Parent() : parent_mem(1) {}
virtual void write() { cout << "Parent: " << parent_mem << endl; }
int parent_mem;
};
class Child : public Parent
{
public:
Child() : child_mem(2) { parent_mem = 2; }
void write() { cout << "Child: " << parent_mem << ", " << child_mem << endl; }
int child_mem;
};
int main(int, char**)
{
// I can have a polymorphic container with pointer semantics
vector<Parent*> pointerVec;
pointerVec.push_back(new Parent());
pointerVec.push_back(new Child());
pointerVec[0]->write();
pointerVec[1]->write();
// Output:
//
// Parent: 1
// Child: 2, 2
// But I can't do it with value semantics
vector<Parent> valueVec;
valueVec.push_back(Parent());
valueVec.push_back(Child()); // gets turned into a Parent object :(
valueVec[0].write();
valueVec[1].write();
// Output:
//
// Parent: 1
// Parent: 2
}
© Stack Overflow or respective owner