OOPortal OOPortal


Operator Overloading  «Prev 

Using a member function to overload a binary operator

In contrast, let us overload binary minus with a member function:
class clock {
   .....
   clock  operator-(clock c);
};

clock clock::operator-(clock c){
   return (tot_secs - c.tot_secs);
}

Remember that there is an implicit first argument. This takes some getting used to. It would have been better to use a friend function for binary minus, because of the symmetrical treatment of both arguments.

Member Functions and User Defined Types

Member functions can be used to interact with data contained within user defined types. User defined types provide flexibility in the divide and conquer scheme in program writing. One programmer can write a user defined type and guarantee an interface while another programmer can write the main program with that expected interface. The two pieces are put together and compiled for usage. User defined types provide encapsulation defined in the Oject Oriented Programming (OOP) paradigm.
The programmer can define functions to perform the operations on those data members to protect the data members within classes. Member functions and functions are names used interchangeably in reference to classes. Function prototypes are declared within the class definition. These prototypes can take the form of non-class functions as well as class suitable prototypes. Functions can be declared and defined within the class definition.
Most functions can have very large definitions and make the class very unreadable. Therefore it is possible to define the function outside of the class definition using the scope resolution operator "::". This scope resolution operator allows a programmer to define the functions somewhere else. This can allow the programmer to provide a header file .h defining the class and a .obj file built from the compiled .cpp file which contains the function definitions. This can hide the implementation and prevent tampering. The user would have to define every function again to change the implementation. Functions within classes can access and modify (unless the function is constant) data members without declaring them, because the data members are already declared in the class.