Monday, September 28, 2015

Chapter 11 - Friend Function and Operator Overloading



LETS LEARN

Friend Functions

Operator Overloading

     Operators that Can be Overloaded

     Operators that Cannot be Overloaded

     Operators that cannot be overloaded by Friend function

Categories Of Overloaded Operators

     (a) Overloading Unary Operator

     (b) Overloading Binary Operator

FRIEND FUNCTIONS

As a general rule, private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, this rule does not affect friends of a class. A friend function of a class is defined outside that class. But it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions of any class.

Friend function is used to access the private members of a class by the non-member functions. It overrides the data hiding concept and are defined external to the class definition. It cannot be accessed with the object name, but can access the members through the object only. It can be declared either in public or private sections. The meaning remains same. Remember that using the scope resolution operator(::), functions of one class can be declared as friend function of another class. One function can be declared friend of more than one class. Friend function can have arguments passed “by value” as well as “by reference”.

Syntax for declaring friend function:

         friend  return-type  function-name ( argument-list ) ;

Syntax for defining friend function:


function-name ( argument-list )  

          {

                      ...............

                  // Body of the function

          }


Syntax for calling the friend function:


function-name ( argument-list ); 

Below is a program on how to access a private member through friend function.


PROGRAM 64


Q. Write a program to declare and input following private-data-members: Name, Employee Number, Salary. Then, without object reference to access the data members, print Employee Number from main function (use a friend function).

 

#include <iostream>

using namespace std;

 

class EmpData

{

          int EmpNumber;

          char Name[20];

          float Salary;

            public:

          void AcceptData();

          /*   Friend Function Declaration   */

          friend  int  GetEmpNumber(EmpData  ob);

 };

 

/*       Friend Function Definition  */

int  GetEmpNumber(EmpData  ob)

{

          return(ob.EmpNumber);

}

void  EmpData :: AcceptData()

{

   cout<<"Enter Employee Name   :  ";

   cin>>Name;

   cout<<"Enter Employee Number :  ";

   cin>>EmpNumber;

   cout<<"Enter Employee Salary :  ";

   cin>>Salary;

}

main()

{

  EmpData obj;

  /* For storing private members in object obj */

  int n;

  obj.AcceptData();

  /*Access private member EmpData through friend function*/

  n = GetEmpNumber(obj);

  cout<<"\n*** Accessing Private member using Friend Function ***\n\n";

  cout<<"Employee Number is :  "<<n;

}


OUTPUT











OPERATOR OVERLOADING

Operator Overloading is a feature that allows the programmer to define a specific C++ Operator with new functionality. 

In C++, you can overload most of the operators so that they perform special operations relative to classes that you create. The ability to overload operators is one of C++’s most powerful features. It provides multiple meaning to the set of predefined operators. Operator overloading allows you to pass different variable types to the same function and produce different results. Operator overloading is common-place among many efficient C++ programmers. It allows you to use the same function name, but with different functionality.


Syntax for declaring an overloaded operator:

returnType operator operatorSymbol ( argument list );

 

Syntax for defining an overloaded operator:

returnType operator operatorSymbol ( argument list )

{

     …… // Body of the function

}

Syntax for calling an overloaded operator:

classObject1 operatorSymbol classObject2;

Note:

(i) The overloaded operator function is called for class-object1,

(ii) class-object2 is passed as the argument/parameter. 

  • Overloaded operator function can be declared as a friend function or as a member function. An operator overloaded function declared & defined as friend   function needs to have at least one parameter that is of class type or a reference to class type. Operator overloading function is always declared in public section. An operator function is created using the keyword operator.


Operators that can be Overloaded

 ^                 =              <                  >                !=            +           

+=              - =              &                 new            delete         -            

%                <=              >=                «                »              *

  &&               ||                 !                  ++              --             / 


  • The precedence of an operator cannot be redefined.
  • The number of operands accepted by the operator cannot be changed.
  • Meaning of an operator cannot be altered when applied to built-in data types.
  • Overloaded operators cannot take default arguments.

Operators that Cannot be Overloaded

         sizeof                Size of operator

         .                       Membership operator

         ::                      Scope resolution operator

         ?:                     Conditional operator

Operators that cannot be overloaded by Friend Function

         =                      Assignment operator

         ( )                    Function call operator

         [ ]                    Subscripting operator

         ->                    Class member access through pointer 

CATEGORIES OF OVERLOADED OPERATORS


       (a) Unary Operator

         (b) Binary Operator

(a) Overloading Unary operator

A unary operator overloaded using a member function takes no arguments. An overloaded unary operator declared as friend function takes one argument.

PROGRAM 65

Q. Overload the unary operator ++  to add any number with 100, instead of the normal value 1. 

#include <iostream>

using namespace std;
class Number
{
    int a, oa;
    public:
    Number()
    {
      cout << " Enter a Number : ";
      cin >> a;
    }
    void DisplayNumber();
    void operator ++();
};
void Number :: operator++()
{
    oa = a + 100;
}
void Number :: DisplayNumber()
{
    cout<<"\n After Operator Overloading ++"<<a<<" = "<<oa;
}
main()
{
  Number n;
  ++n;
  n.DisplayNumber();
}

 

OUTPUT

 






(b) Overloading Binary Operator

The binary operator is overloaded using a member function by passing one argument. An overloaded binary operator declared as friend function takes two arguments.

PROGRAM 66

Q. Write a program to assign 2 numbers each into object1 and object2 of a class through its constructor. Overload the binary operator + to add the first numbers of object1 and object2. Then add the second numbers of object1 and object2.  Display the numbers after the overloaded operator is applied.

 

#include <iostream>

using namespace std;

class Number

{

         int p,q;

         public:

         /*Default constructor for creating object without passing argument*/

         Number()

         {

              p=0;

              q=0;

         }

         Number(int a, int b)

         {

              p=a;

              q=b;

            }

            void DisplayNumber();

            Number operator +(Number ob);

 };

/* Over loaded function for adding two objects */

Number Number :: operator+(Number ob)

{

         Number obt;

         obt.p=p+ob.p;

         obt.q=q+ob.q;

         return(obt);

  }

void Number :: DisplayNumber()

{

         cout<<"\n Number 1  : "<<p;

         cout<<"\n Number 2  : "<<q;

}

main()

{

         Number ob1(100,200);

         Number ob2(11,22);

         Number obr;

         cout<< "\nBefore operator overloading \n";

         ob1.DisplayNumber();

         /*  obr is object for storing result after adding ob1 and ob2 values */

         obr=ob1+ob2;

         cout<< "\n\nAfter operator overloading \n";

         obr.DisplayNumber();

 }

 

OUTPUT

















No comments:

Post a Comment