Question

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.

Was it helpful?

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.

OTHER TIPS

What you want isn't a hierarchy of classes. It is impossible to assign to a base object to get the properties of a derived object. The base object will always remain a base object. If you want to have polymorphic behaviour but keep sensible value semantics, encapsulate the polymorphism within a non-polymorphic class:

class A_impl;

class A {
public:
    //Public interface:
    //...

private:
    //Assuming `value_ptr` similar to
    //https://bitbucket.org/martinhofernandes/wheels/src/17aee21522ce8d07c7a74b138e528fadf04d62ed/include/wheels/smart_ptr/value_ptr.h%2B%2B?at=default
    value_ptr<A_impl> impl;
};


class A_impl {
public:
    //Implementation interface:
    //virtual ...
    //virtual ~A_impl() {}
};

class B : public A_impl {
public:
    //Implementation:
    //...
};

you shoud write copy construct operator.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top