c++ array of class - copy between array elements

I'm lost --> hope someone can help me.
I have an array of class PT like this:


PT *classarray;
classarray = new PT[15];

where class PT is:

class PT
{
public:
PT(void);
~PT(void);

BB *B; //another class

//lots of other members

int xxx;
bool yyy;
};

After several operations -- I want to set array 10 equal to array 9. So..

classarray [10] = classarray [9];

However, when I make changes to classarray [9] --> are are reflected in classarray [10].

So, I gather that I'm setting the pointers = to each other.

I'm now considering writing a function to copy all of the elements one by one. The trouble is this class has so many memebers and sub classes and pointers etc -- that I want to avoid if possible doing that.

Any suggestions -- THANKS


Last edited on
If you want to do a bitwise copy of the object, you have no choice but to overload the assignment operator.
In this case, the prototype would be PT &operator=(const PT &);
You need to return *this, at the end.
I think what you need is a copy constructor, especially if you have pointers in your class because you need determine who owns what the pointers point to. If you don't have a copy constructor and you do a bitwise copy you get two instances pointing to the same place e.g. B in your example would point to same object.

1
2
3
4
5
6
7
PT(const PT &in)
{
    if (this != &in)
   { 
       ...
   }
}


It is also better to hide your members a.k.a. "not show your private parts" and instead access them via accessors, this makes your life easier and the usage of your classes more friendlier.

e.g.

1
2
int xxx() const { return _xxx; }
void xxx(int x) { _xxx=x; }


Also avoid doing monolithic classes, classes shouldn't be all encompassing monstrosities with lots of member variables etc, that it is an indication that your design is flawed and will probably cause you a headache later.

As helios said an assignment operator is also a must. If you have default ctor, copy ctor and assignment operator in all your classes, sub classes etc you will have better control as each class will be self-contained and errors easier to detect.

Last edited on
Generally if you need to write a non-default assignment operator, then you need to write a copy constructor also, and vice versa.

However, the if( this != &in ) check is not needed in the copy constructor.

Topic archived. No new replies allowed.