0

I have this code:

the output of the code is:

cons intcons op+ intcons ; copycons op+ intcons op+= ; get_val 3

class declaration::

#include<iostream>
using namespace std;

class Int {
public:
// constructors
Int() : val_(0) { cout << "cons "; }
Int(int n) { val_ = n; cout << "intcons "; }
Int(const Int &v) : val_(v.val_) { cout << "copycons "; }
Int(Int &&v_) { val_ = v_.val_; cout << "mov ctor " ; };

// operations
int get_val() {
    cout << "get_val "; return val_;
}
Int operator+(const Int &v) {
    cout << "op+ ";
    return Int(val_ + v.val_);
}
Int & operator=(const Int &v) {
    cout << "op= ";
    if (this != &v) { 
        val_ = v.val_; 
    }
    return *this;
}
Int & operator+=(const Int &v) {
    cout << "op+= ";
    val_ += v.val_;
    return *this;
}
private:
int val_; // value stored in this Int

};

and this is main:

int main(){
Int zero;
Int one = zero + 1;
cout << ";\n";
Int two = zero;
two += one + one;
cout << ";\n";
cout << two.get_val() + 1; cout << endl;
return 0;
}

I was looking at the codes output, and I could agree with each operation that happens and with every output. but one thing isn't clear to me at all. I wonder, why in the first line of the output there isn't use with the copy c'tor?

at first I though maybe it is a move c'tor. then I built one and it doesn't seemed like the compiler was using it.

can anyone please tell me what is going on? thank you!

Tal Alfi
  • 35
  • 6
  • Much wisdom on operator overloading: [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – user4581301 Sep 24 '18 at 20:49

1 Answers1

4

I think you are confusing the assignment operator with the copy constructor. Int two = zero; will cause the copy constructor to be called.

two = zero or two = 1 will cause the assignment operator to be called.

https://techdifferences.com/difference-between-copy-constructor-and-assignment-operator.html

Yucel_K
  • 688
  • 9
  • 17
  • thanks for your answer, the codes output is the following: cons intcons op+ intcons;(endl) copycons op+ intcons op+=; (endl) get_val 3 (endl) do you have any idea why in the first line of output the operator '='didnt take action? – Tal Alfi Sep 24 '18 at 20:29
  • 1
    as its been described on the link, for the assignment operator to work, both objects has to be initialized. so when the statement `int two = one` executed, the two is not initialized yet. hence its not calling the overloaded operator. instead its calling the copy constructor. – Yucel_K Sep 24 '18 at 20:34
  • @TalAlfi your code doesn't contain` operator=` calls, only +=. `Int two = zero;` is not assignment , it's an initialziation, a call to constructor happens – Swift - Friday Pie Sep 24 '18 at 20:35
  • it seems also performs some elision and move never happens because compiler constructs object in place instead. – Swift - Friday Pie Sep 24 '18 at 20:52