Alberto Tiraboschi
Alberto Tiraboschi

Reputation: 303

Operator equals overloading c++ apparently not working

Can someone explain me why the cout doesn't get called here?

#include <iostream>

using namespace std;

class Test {
public:
    int a = 1;

    Test &operator=(const Test &other) {
        cout << "overloading here" << endl;
        return *this;
    }
};


int main() {
    Test t1;
    Test &t3 = t1;
    return 0;
}

Upvotes: 0

Views: 101

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

    Test &t3 = t1;

is creating a reference for Test and initiaizing that. = operator is not used there. There are no cout other than inside operator=, so cout won't be called.

Note that

    Test t3 = t1;

(without &) will also not call operator= because this is an initialization of object and a constructor is used for that.

To use operator=, you should do like

    Test t3;
    t3 = t1;

Upvotes: 6

Related Questions