-4

The following is a sample code for operator overloading. what does the "&" means in the syntax

complx operator+(const complx&) const; ?

#include <iostream>
using namespace std;
class complx
{
      double real,
             imag;
public:
      complx( double real = 0., double imag = 0.); // constructor
      complx operator+(const complx&) const;       // operator+()
};

// define constructor
complx::complx( double r, double i )
{
      real = r; imag = i;
}

// define overloaded + (plus) operator
complx complx::operator+ (const complx& c) const
{
      complx result;
      result.real = (this->real + c.real);
      result.imag = (this->imag + c.imag);
      return result;

}

int main()
{
      complx x(4,4);
      complx y(6,6);
      complx z = x + y; // calls complx::operator+()
}
prgbenz
  • 1,129
  • 4
  • 13
  • 27
  • 5
    That's a reference. Any [decent introductory C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) should cover this. – R. Martinho Fernandes Apr 22 '13 at 09:24
  • 1
    Wikipedia also has decent information for beginners: [operators wiki](http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Member_and_pointer_operators) – Dariusz Apr 22 '13 at 09:26

3 Answers3

2

That means that you are passing a reference to a variable, instead of a copy of it.

SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
2
(const complx&)
  1. You are passing the value by reference.

  2. Reference is just an alias to the original object.

  3. Extra copy operation is avoided here. If you have used 'pass by value' like : (const complex ), then the copy constructor of complex is invoked for formal parameters.

Hope this helps to some extend.

Whoami
  • 13,930
  • 19
  • 84
  • 140
0

That is called as pass by reference and it is not specific to operator overloading. It is one of the ways you would pass arguments to a function [ 1.Pass by Copy, 2.Pass by address, 3.Pass by Reference ]. With C you make use of pointers when you want your original argument value to be modified when you modify it within a function. But Cpp also provides pass by reference, the name appended with & acts like an alternate name to the passed argument. [and also saves you from all that dereferencing and stuff associated with pointers]

Suvarna Pattayil
  • 5,136
  • 5
  • 32
  • 59