op= thumb rules' question

Hello everyone,
I was reading my OOP lectures, getting ready for the course test and I came through the implementation of op= and I have a question.
There the thumb rules for the implementation of the op=(free old memory, allocate new memory, work with new memory, etc), as shown in here:

1
2
3
4
5
6
7
8
String& String::operator=(const String& rhs){ //string's op=
if (this==&rhs) return *this;
len = rhs.len;
delete[] s;
s = new char[len +1];
strcpy(s, rhs.s);
return *this;
}


After seeing this example I was wondering why do I need relocate memory for class which I know it's pointers point to a constant-size array, like this example shows:

1
2
3
4
5
6
7
//how do I implement an op= for this class: 
class A{ 
int* a;
double* b;  
public: A() { a=new int[3]; 
b=new double [5]; }
}


SO, the question is why do I need to relocate new memory and work with it(I emailed my lecturer and she told me if I won't do it(relocate memory and work with if) it may cause other problems rather than MEMORY LEAK).

Thanks!!
if you sure that your array is fixed size and second instance of your class have array of the same size as first, you can do simply:
1
2
3
4
5
6
7
8
A& A::operator=(const A& rhs)
{
    for(int i(0); i < 3; ++i)
        this->a[i] = rhs.a[i];
    for(int i(0); i < 5; ++i)
        this->b[i] = rhs.b[i];
    return *this;
}
Last edited on
Or simply
1
2
3
4
class A{
   int a[3];
   double b[5];
};
no need to code destructor, copy-constructor or assignment operator.
Last edited on
Topic archived. No new replies allowed.