user4603522
user4603522

Reputation:

C++ assignment operator and overloading

I was wondering why the following code is being compiled successfully.

#include <iostream>
#include <cassert>
using namespace std;

class Integer{
private:
    int i;
public:
    Integer(int value):i(value){}
    // unary or binary
    const Integer operator+(const Integer& rv){
        cout << "operator+"<< endl;
        return Integer(i + rv.i);
    }
    // Binary Operator
    Integer& operator+=(const Integer& rv){
        cout << "operator+=" << endl;
        i += rv.i;
        return *this;
    }
    ostream& operator<<(ostream& lv){
        lv << i;
        return lv;
    }
    friend ostream& operator<< (ostream& lv, Integer& rv);
};

ostream& operator<< (ostream& lv,Integer& rv){
    return lv << rv.i;
}

int main(){
    cout << "using operator overloading"<< endl;

    Integer c(0), a(4), b(5);
    Integer d = 8;
    c = a + b;
    cout << c << endl;
    cout << d << endl;
}

I dont understand why d = 8 is possible. d is a user defined type. I did not overloaded the assignment oeprator for the Integer class. Is there a default overloaded operator?

Upvotes: 4

Views: 120

Answers (3)

decltype_auto
decltype_auto

Reputation: 1736

I dont understand why d = 8 is possible. d is a user defined type.

Just instrument your code a little more and also trace the ctor calls.

#include <iostream>
#include <cassert>
using namespace std;

class Integer{
private:
    int i;
public:
    Integer(int value):i(value){
        cout << "Integer(int) called with " << value << endl; 
    }
    // unary or binary
    const Integer operator+(const Integer& rv){
        cout << "operator+"<< endl;
        return Integer(i + rv.i);
    }
    // Binary Operator
    Integer& operator+=(const Integer& rv){
        cout << "operator+=" << endl;
        i += rv.i;
        return *this;
    }
    ostream& operator<<(ostream& lv){
        lv << i;
        return lv;
    }
    friend ostream& operator<< (ostream& lv, Integer& rv);
};

ostream& operator<< (ostream& lv,Integer& rv){
    return lv << rv.i;
}

int main(){
    Integer d = 8;
     cout << d << endl;
}

output:

Integer(int) called with 8
8

live at Coliru's

The presumed assignment of the immediate 8 in fact causes the non-explicit Integer(int) ctor to be called with 8 as its argument.

Upvotes: 1

Paolo M
Paolo M

Reputation: 12757

You have not declared the Integer constructor explicit, so it acts as an implicit conversion from int to Integer.

If you declare your constructor

explicit Integer(int value);

the compiler fires the error:

error: conversion from ‘int’ to non-scalar type ‘Integer’ requested

Upvotes: 7

ramana_k
ramana_k

Reputation: 1933

Your constructor defines conversion from int to Integer

Integer(int value):i(value){}

Upvotes: 2

Related Questions