Operator Overloading
- A variable's type specifies a:
- set of values a variable can store.
- set of values you can perform
- egs int type: you can add, subtract etc.
- When you define a class in a program, you are essentially defining a new type.
- operator overloading is the process of changing the meaning of an operator for a specific class.
- When you overload an operator for a class, the operator's function does not change for other variable types; C++ compiler will determine which operation to employ based on the variable type.
- operators you cannot overload object.member, classname::member, ?:
- To overload an operator, you must define a class to which the operator will be assigned.
- When you overload an operator, the overload is in effect for the class in which it is defined; if the program uses the operator with non-class variables, the operator's original definition is used.
- To overload an operator you can use the C++ operator keyword to define a class method.
Private members and friends
- private class members can only be accessed using class members.
- by using private class members as often as possible, you reduce the possibility of a program misusing a member's value, since the program must access the member using an interface function.
- There are times when you significantly increase the efficiency of a program by allowing one class to access the private members of another class directly. This avoids the processing overhead to invoke interface functions. For such cases, C++ lets you define a class as friend of another.
Ihe C++ compiler must be informed that a particular class is a friend by placing the keyword friend and the class name within the public members of a class function.
- To limit the number of friend methods that can access the private members, C++ lets you specify friend functions.
- To declare a friend function, you specify the friend keyword followed by the function's prototype, for the function that needs to access class private members.
- Since a friend function is external to a class, it does not lie within the scope of the class and is implemented as a standard function; the keyword friend is not repeated in the function declaration.
- A friend function gains access to members of the class only by being passed objects as parameters and using the dot notation to reference the class member.
- In order to overload an unary operator as a friend, pass the operand as a parameter; when overloading a binary operator as a friend, pass both operands as parameters.