I'm trying to clean up my coding a bit for a program I'm working on. Here's an example of my code (not my exact code, but I've adapted it to an example):
class Example
{
private:
double* group;
int number;
public:
Example() {group=new double[1]; number=0;};
Example(const Example& ex);
Example& Example::operator=(const Example& ex);
void function1(const Example& ex);
};
Example::Example(const Example& ex)
{
number=ex.number;
if(ex.group)
{
group=new double[number+1];
for(int i=number;i>=0;i--)
group[i]=ex.group[i];
}
else group=0;
}
Example& Example::operator=(const Example& ex)
{
if(this == &ex)
return *this;
delete [] group;
number=ex.number;
if(group != ex.group)
{
group=new double[number+1];
for(int i=number;i>=0;i--)
group[i]=ex.group[i];
}
else group=0;
return *this;
}
I want to be able to create a copy object of Example that is the same as the original. I've created a copy constructor and overloaded the assignment operator, but if I call the member function from within main, then in my definition of the member function function1, how can I create a copy for computational purposes? This is what I've been doing, but I feel like there's an easier way:
Example copy2;
copy2.number=number;
copy2.group=new double[number+1];
for(int i=number;i>=0;i--)
copy2.group[i]=group[i];
(Sorry if this is confusing, let me know and I'll try to explain a different way if need be)
Thanks!