I Have some doubt in operator overloading in c++.
#include<iostream>
using namespace std;
class ex
{
int i;
public:
ex(){}
void operator+(ex ob);
void seti(int x);
int geti();
};
void ex::operator+(ex ob)
{
this->i+=ob.i;
}
void ex::seti(int x)
{
i=x;
}
int ex::geti()
{
return i;
}
int main()
{
ex ob1,ob2;
ob1.seti(2);
ob2.seti(2);
ob1+ob2;
cout<<"ob1:"<<ob1.geti();
cout<<"\nob2:"<<ob2.geti();
return 0;
}
output:
ob1:4
ob2:2
Process returned 0 (0x0) execution time : 0.400 s
Press any key to continue.
Here the left of the operator + that is ob1 is passed implicitly (this pointer) to the function and ob2 is passed through the parameter to the function I am OK with that.
But see the following code.
#include<iostream>
using namespace std;
class ex
{
int i;
public:
ex(){}
void operator++();
void seti(int x);
int geti();
};
void ex::operator++()
{
this->i++;
}
void ex::seti(int x)
{
i=x;
}
int ex::geti()
{
return i;
}
int main()
{
ex ob1;
ob1.seti(2);
ob1++;
cout<<"ob1:"<<ob1.geti();
return 0;
}
When i compile above Shows This error:
D:\Users\srilakshmikanthan.p\Documents\source code\ex.cpp||In function 'int main()':|
D:\Users\srilakshmikanthan.p\Documents\source code\ex.cpp|37|error: no 'operator++(int)' declared
for postfix '++' [-fpermissive]|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 2 second(s)) ===|
When i change the line ob1++; to ++ob1; It will compile successfully and shows result 3.
My doubt is In operator overloading the left side of the overloaded operator is passed through implicitly(this pointer) to the function but why this is not happens here. The compiler says change the line ob1++; to postfix like ++ob1; but the object in right.
Please help me.