Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this conversion happening?

#include<iostream>

using namespace std;

class test
{
  int a, b;
public:

  test() {
    a=4; b=5;
  }

  test(int i,int j=0) {
    a=i; b=j;
  }

  test operator +(test c) {
     test temp;
     temp.a=a+c.a;
     temp.b=b+c.b;
     return temp;
  }

  void print() {
    cout << a << b;
  }
};

int main() {
  test t1, t2(2,3), t3;
  t3 = t1+2;
  t3.print();
  return 0;
}

How can the compiler accept a statement like t3=t1+2; where 2 is not an object?

like image 201
shubhendu mahajan Avatar asked Dec 17 '22 09:12

shubhendu mahajan


2 Answers

The compiler sees you are invoking operator+(test) and attempts to implicitly convert the 2 to a test successfully using your test(int i,int j=0) constructor.

If you want to make the conversion explicit, you must change the constructor to explicit test(int i, int j=0). In this case, your code would generate a compiler error because 2 cannot be implicitly converted to test. You would need to change the expression to t1 + test(2).

like image 57
tenfour Avatar answered Dec 31 '22 00:12

tenfour


Because test(int i,int j=0) is a constructor that takes one or two arguments, so a test object is created from 2. In the next stage test operator +(test c) is called.

like image 45
Lindydancer Avatar answered Dec 31 '22 02:12

Lindydancer