can i have polymorphic containers value semantics c++?


as whole rule, i move controlling value rather pointer semantics c++ (ie controlling vector<class> instead vector<class*>). wholly slight detriment opening some-more finished adult carrying remember mislay boldly allocated objects.



unfortunately, value collections don't work wish store accumulation vigilant forms get common base. instance below.



#include <iostream>

using namespace std;

class parent
{
public:
parent() : parent_mem(1) {}
practical vacant write() { cout << "parent: " << parent_mem << endl; }
int parent_mem;
};

class child : open parent
{
public:
child() : child_mem(2) { parent_mem = 2; }
vacant write() { cout << "child: " << parent_mem << ", " << child_mem << endl; }

int child_mem;
};

int main(int, char**)
{
// i have polymorphic enclosing 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

// nonetheless i can't value semantics

vector<parent> valuevec;

valuevec.push_back(parent());
valuevec.push_back(child()); // gets incited progenitor vigilant :(

valuevec[0].write();
valuevec[1].write();

// output:
//
// parent: 1
// parent: 2

}


my doubt is: i have have cake (value semantics) eat too (polymorphic containers)? i have pointers?



Comments

Popular posts from this blog

list macos calm editors formula editors

how hibernate @any-related annotations?

why does floated <input> control floated component slip over too distant right ie7, nonetheless firefox?