Page 67 - DCAP404 _Object Oriented Programming
P. 67

Object-oriented Programming




                    Notes          Now the next instruction in the main program will get executed. Jumping back and forth keeping
                                   track of where to jump means that there is an overhead in elapsed time to functions. When the
                                   function is declared inline the compiler replaces the function call with the corresponding function
                                   code. As a result the program does not have to spend time to jump to another location to execute
                                   the function and then come back. But there is a memory overhead. If the function is called n
                                   times in the program then it is copied n times making the program code or in particular executable
                                   code large. If the value of n is large, there is a lot of memory overhead.




                                      Task  How do you tell the compiler to make a non-member function inline?

                                   The following program demonstrates the use of inline function to calculate square of an input
                                   number.

                                   #include  <iostream.h>
                                   #include  <conio.h>
                                   inline  float  square(float  a)
                                   {
                                   retum  (a  *  a);
                                   }
                                   void  main()

                                   {
                                   float  b;
                                   cout  <<“  Enter  a  number”;
                                   cin  >>  b;
                                   a  =  square(b);  .
                                                 cout  <<  “\nThe  square  of  “  <<  b  <<  “is  “  <<  a;
                                   }
                                   You should see the output as shown below.

                                   Enter a number 1.2
                                   The square of 1.2 is 1.44
                                   Actually, compiler compiles the code by inserting the function definition at the place where it is
                                   called as shown below.
                                   #include  <iostream.h>
                                   #include  <conio.h>
                                   inline  float  square(float  a)
                                   {
                                   retum  (a  *  a);

                                   }
                                   void  main()
                                   {



          60                                LOVELY PROFESSIONAL UNIVERSITY
   62   63   64   65   66   67   68   69   70   71   72