# Thread: Conversion and Constructor Functions

1. ## Conversion and Constructor Functions

Hi,
Code:
```class X
{
int i;
public:
X(const int& val) : i(val)
{}
X operator+(const X&);
};

X X::operator+(const X &ob)
{
return X(i + ob.i);
}

int main()
{
X ob1(10), ob2;

ob1 + 30; // this works like ob1 + X(30);

30 + ob1; // NOT working in VC++. Any idea why???

return 0;
}```
Can any body throw any light as to why if
ob1 + 30 works why not 30 + ob1

2. >> X operator+(const X&);

This line overloads the '+' operator, but the object can only be on the left, which is why the following doesn't work : 30 + ob1;

3. ## I got the answer

This works

If the operator requires an lvalue as their left-hand operand, then its got to be a member function. If its got to work on both the way, it must be a non-member function.

Code:
```class X
{
int i;
public:
X(int val = 0) : i(val)
{}
int ival() const
{
return i;
}
};

X operator+(const X&ob1, const X &ob2)
{
return X(ob1.ival() + ob2.ival());
}

int main()
{
X ob1(10), ob2;

ob1 + 10; // works
10 + ob1; // also works

return 0;
}```

4. Greetings,

'30 + ob' does not work, in this case, because the compiler is looking for an '+' operator wich takes an left operand of type int and a right operand of type X, and there isn't one.
This because of the way the '+' operator was defined. The correct way of doing what you want is by making the '+' operator a friend, e.g.
Code:
```class X {
public:
X(const int& val) : i(val) {}

friend X operator + (const X& ob1, const X& ob2)
{ return X(ob1.i + ob2.i); }
private:
int i;
};```
Now, this way the compiler knows how to apply the operator to both '30+ob' and 'ob+30'.

5. ## I beg to differ :)

Originally posted by augur
Greetings,

'30 + ob' does not work, in this case, because the compiler is looking for an '+' operator wich takes an left operand of type int and a right operand of type X, and there isn't one.
This because of the way the '+' operator was defined.
Now, this way the compiler knows how to apply the operator to both '30+ob' and 'ob+30'.
Hi, I had posted this question, and having said that, I have also answered the question after some R & D. So do take time to read the second post that I have posted. That must work.

Well in anycase, your program would also work.

ob + 30 is translated as ob + x(30); // if its a member function

30 + ob is translated as X(30) + ob; // if its a non-member function with two arguments of type X

Note: There are multiple ways to solve this problem.