-3

I am new in C++ programming , I want to return object which was passed by default in operator overloading. Please help me on that.....

eg.

adi operator+(adi& s2){return s1;} 

main()
{
  s3=s1+s2;
}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • 5
    Not sure what you're asking exactly, but your operator should take two arguments. I'd also recommend you take them by `const` reference. – Fred Larson Mar 07 '14 at 16:38
  • 2
    Take a look at [this](http://stackoverflow.com/questions/4421706/operator-overloading) question. It has more information about overloading operators. – coln Mar 07 '14 at 16:38
  • 1
    caebli3's link's good - specifically, look for the "Binary operators" heading in the top answer. – Tony Delroy Mar 07 '14 at 16:43
  • When I used *return this. I made it. I have successfully returned s1 which was implicitly passed to overloaded operator function. – AdityaKhursale Mar 07 '14 at 17:45

2 Answers2

0

You either implement operator+ as a class member

class A {
  A operator+(const A& rhs) const {
    A result; // do something with a
    // Pick one
    return result; // returns new object
    return rhs; // returns rhs parameter
    return *this; // returns current object
  }
};

Or as a non-member

A operator+(const A& a, const A& b) {
    A result; // do something with a
    return result; // returns new object
}
Blaz Bratanic
  • 2,279
  • 12
  • 17
0

It will look the following way

adi operator+( const adi &s2) const
{ 
   adi temp;
/* some calculations with temp*/ 

   return temp;
} 

The symantic is the following: you create a new object that will be the sum of the object that calls the operator that is this ans the object passed to the operator as an argument. Neither the original object nor the arument should be changed.

Also the operator can be define as a non-member function. For example

adi operator+( const adi &s1, const adi &s2)
{ 
   adi temp;
/* some calculations with temp*/ 

   return temp;
} 
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335