Return value of overloaded assignment operator

Hello,

when learning C++ I've been using a MyClass& return value when overloading the assignment operator for a class MyClass. But why are we doing this?

Consider the following class (note that I've replaced Dataset& with void here for the overloading of the assignment operator) :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Dataset {
private:
    double *y;
    int N;
public:
    Dataset(int N);
    Dataset(const Dataset &other);
    ~Dataset();
    void operator=(const Dataset& rhs);
    double interpolate(double x);
    int getSize() const { return N; }
    double& operator[](int i) { return y[i]; }
};


and implementation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Dataset::Dataset(int N) : N{N} {
    
    y = new double[N] {};
}

Dataset::Dataset(const Dataset& other) {
    this->N = other.N;
    this->y = new double[N];
    
    for (int i = 0; i < N; i++) {
        this->y[i] = other.y[i];
    }
    
}

Dataset::~Dataset() {
    delete [] y;
    
}

void Dataset::operator=(const Dataset& rhs) {
    this->N = rhs.N;
    delete [] this->y;
    this-> y = new double[N];
    for (int i = 0; i < N; i++) {
        y[i] = rhs.y[i];
    }
    //return *this;
}


From main:
1
2
3
4
5
Dataset data{10};
    Dataset d2{100};
    Dataset dr = data;
    
    d2 = dr;


and it runs without errors. So why are we usually returning &MyClass when overloading the assignment operator, and not just void it?

Last edited on
With this return type you may cascade the operator:

1
2
3
4
5
6
Dataset data{10};
    Dataset d1;
    Dataset d2{100};
    Dataset dr = data;
    
    d1 = d2 = dr;


Without the compiler would throw an error.
Last edited on
So it is basically for "chaining" operations, just like for overloading the << operator?
Indeed.


PS. You are not systematic:
1
2
3
4
5
6
7
8
Dataset::Dataset(int N) : N{N} {
    
    y = new double[N] {};
}

Dataset::Dataset(const Dataset& other) {
    this->N = other.N;
    this->y = new double[N];


Based on the first, one would expect:
1
2
3
4
Dataset::Dataset(const Dataset& other)
 : N{other.N}
{
    this->y = new double[N];

Or perhaps even:
1
2
3
Dataset::Dataset(const Dataset& other)
 : y{new double[other.N]}, N{other.N}
{


On the assignment, what if this->N >= rhs.N? Is deallocate+allocate absolutely necessary in that situation?
Last edited on
Topic archived. No new replies allowed.