4

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?

1

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

Comments

2

Your constructor defines conversion from int to Integer

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

Comments

1

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.

Comments