koppe74
2010-03-29 03:31:45 UTC
One thing, objects (created from a class) and referred by name (e.g. sys1), is the name then a pointer (like an array) or an actual instance (like an int)?
I have one class (Sys) that contains a dynamic-array of instances of another class (Rad) (or, it's supposed to). I want to copy the content of one instance of the Sys-class to another (possibly empty) instance of the same class... and I'm obviously doing something wrong.
For one attempt, I was "double-deleting", so I'd obviously made a shallow copy. For the other attempt, I failed to copy over the content of the Rad-instances in the dynamic array.
So how should this be done *correctly*? Hos should the copy-constructor be? How should the constructor be? Do I need to overload =-operator? Should I use pointer and new? How should the assignment be done (e.g. "s3=s1", "s3=Sys(s1)", or something else)?
I have the following two classes:
class Rad {
private:
int data[11];
public:
//Nothing interesting, using default constr, destr and cpyconstr
};
//The methods are not really written inline...
class Sys {
private:
int size;
Rad *rad_ptr;
public:
Sys()
{
size=0;
row_ptr=NULL;
};
Sys (int sz)
{
size=sz;
row_ptr=new Rad[size];
};
Sys(Sys &src) //This doesn't work... Why?!?
{
size=src.size;
row_array=new Rad[size];
for(int i; i
};
~Sys()
{
delete [] row_ptr;
};
}; //End class...
main()
{
Sys s1(10);
Sys s2(10);
Sys s3;
s1.initiate();
s2.initiate();
//This is were I get stuck...
//I want to at least be able
//to copy s1 to s3 (empty),
//but preferably also be able
//to copy s1 to s2 (overwrite).
//These doesn't work... What am I missing?
s2=s1;
s3=s1;
//or...
s2=Sys(s1);
s3=Sys(s1);
//I'm willing to use pointers instead...
//Doesn't work either...
s3ptr=new Sys(s1);
return 0;
}