Search code examples
c++inheritanceassignment-operatorobject-slicing

Proper way to use operator = in derived class and slicing


So I have a base class that has a private member and a derived class that also has some member, the base class defines an operator =, and this is my questions:

Is this the proper way to do this or is there a better way? Do I commit any slicing along the way?

class A
{
private:
int* Arr;
public:
A(){
    Arr=new int[10];
    for(int i=0;i<10;i++){
        Arr[i]=2*i;
    }
}
const A& operator=(const A& a){
    delete []Arr;
    Arr=new int[10];
    for(int i=0;i<10;i++){
        Arr[i]=a.Arr[i];
    }
    return *this;
}
};

class B: public A
{
private:
int * Arr2;
public:
B(){
    Arr2=new int[10];
    for(int i=0;i<10;i++){
        Arr2[i]=3*i;
    }
}
const B& operator=(const B& b){
    A::operator=(b);
    delete []Arr2;
    Arr2=new int[10];
    for(int i=0;i<10;i++){
        Arr2[i]=b.Arr2[i];
    }
    return *this;
}   
};

I know this ain't a perfect code but i just wrote a simple one for the question.


Solution

  • Well after much research I have come to this conclusions:

    While this use of the base class assignment operator will work properly

    A::operator=(b)
    

    The code will still need to provide a proper exception-safe, self-assignment-safe guarantee as it mentioned in the comments.

    Moreover since we need to implement an assignment operator that also means by the rule of three we will need to implement a copy-constructor and as mentioned here that will cause an unnecessary code duplication.

    So how do we solve all this problems (and probably a few more..) ? Best why I found is to use Copy-and-Swap-Idiom. I believe no further explanation is needed beyond what is provided in that post.