dimanche 15 mars 2015

Storing polymoprhic data types into a unique_ptr vector


I'm having issues trying to build a program using a Unique_ptr vector to hold data from multiple classes that are derived from the same base class. I'm pretty sure the concept is correct, so I can avoid slicing my data, but I'm not sure what exactly I'm doing wrong here. Also I'm not sure how I'm supposed to pass a unique_ptr to a function to read it or write it. Any assistance would be greatly appreciated. (Edit, made the code actually comprehensible, sorry for that!)



#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <memory>
using namespace std;


class Base
{
public:
Base();
Base(int x, int y, string z) :Z(z), Y(y), X(x){}
virtual void printstuff(){cout << X << Y << Z; system("pause"); }
virtual ~Base(){}
protected:
int X, Y;
string Z;
};

class Derrived : public Base
{
public:
Derrived();
Derrived(int x, int y, string z, int a, int c) : Base(x, y, z), changeable(c), A(a){}
virtual void printstuff(){cout << X << Y << Z << changeable << A;}
int changeable;
~Derrived(){}
private:
int A;
};

void otherfunction(vector<unique_ptr<Base>>&);

void main()
{
vector<unique_ptr<Base>> array1;
array1.emplace_back(new Derrived (1, 2, "check", 3, 5));
otherfunction(array1);
array1[0]->printstuff();
system("pause");
}



void otherfunction(vector<unique_ptr<Base>>& var1)
{
dynamic_cast<Derrived &>(*var1[0]).changeable = 3;
}


I want the output statement to be 3 for changeable, I'm getting an error C2664 for some reason so I'm not sure what exactly I'm doing wrong, as it doesn't reference a specfic line in my code (the line it references is line 600 of xmemory.h). A copy of the actual code can be found here: Link to the actual code.


Update: The code above compiles and runs properly, however the method is anything but safe and can result in serious errors throughout the program. The program was completely written from the ground up using multiple standard arrays to hold individual classes instead of one vector storing multiple classes.




Aucun commentaire:

Enregistrer un commentaire