Operator Methods

aka Operator member functions

 

To make a class's code more readable, it is suggested that its methods be declared as prototypes within the class and that their implementation is external to the class.

 

Methods then gain access using the scope resolution operator :: e.g. void myClass::getValue(){return myVal;}  This effectively makes the external member a class method, but is it simply being defined externally, for readability.

 

Other functions can also gain access to a class's members by declaring their prototype as a friend within the class.

 

This goes the same for operator methods, which in general can be coded in this manner. However, some operators can only be defined as being class members, that is belonging to the class using the scope resolution operator ::, since they require an lvalue as the first operand, those being:

 

=, [], (), ->

 

new, delete, new[], delete[]
It has also been suggested that it is better to declare methods as friends, when the operator does not modify the operands, as it tries to make the code more readable by using explicitly listed parameters (as opposed to implicit or by the use of the this self reference pointer object).

 

  • If a unary operator is overloaded using a member function, it takes no arguments. If it is overloaded using a global function, it takes one argument.
  • If a binary operator is overloaded using a member function, it takes one argument. If it is overloaded using a global function, it takes two arguments.

Another aspect of declaring a method with class scope that is that it utilises the (generally considered hidden) this self referencing pointer object. Thus, the following two code snippets achieve similar functionality but use different techniques to do so:

 

using member function using friend function
#include <iostream>
using namespace std; 

 

 

class Speed {

private:

int turbo ;

public:

Speed(int mph = 165) : turbo(mph) { }

Speed operator+(int) ;

int getVal(){return turbo;}

} ;

 

//member function, using scope resolution ::
Speed Speed::operator +(int a) {

return Speed(this->turbo + a);

}

 

int main() {

Speed a ;
Speed b = a + 25 ;

cout << "Turbo speed: " << b.getVal() << endl ;

return 0 ;

}

#include <iostream> 

using namespace std;

 

 

class Speed {

private:

int turbo ;

public:

Speed(int mph = 165) : turbo(mph) { }

friend Speed operator+(const Speed &, int);

int getVal(){return turbo;}

} ;

 

//friend function, NOT a member function
Speed operator+(const Speed &faster, int a) {

return Speed(faster.turbo + a) ;

}

 

int main() {

Speed a ;
Speed b = a + 25 ;

cout << "Turbo speed: " << b.getVal() << endl ;

return 0 ;

}

Compile & Run:

Turbo speed: 190

 

Notice how the member function only requires one parameter since it is being self referenced using the this pointer. Whereas, the friend function requires both the calling object and the integer value as its parameters.

Leave a Reply