May 2018

Function overloading in C++ Programming

Overloading refers to the use of the same thing for a different purpose. When the same  function name is used for different tasks this is known as function overloading. Function overloading is one of the important features of C++ and any other OO languages.

When an overloaded function is called the function with matching arguments and return type is invoked. e.g.
void border(); //function with no arguments
void border(int ); // function with one int argument
void border(float); //function with one float argument
void border(int, float);// function with one int and one float arguments

 For overloading a function prototype for each and the definition for each function that share same name is compulsory.

//function overloading
//multiple function with same name

#include<iostream.h>
#include<conio.h>
int max(int ,int);
long max(long, long);
float max(float,float);
char max(char,char);
void main()
{  
return(i1>i2?i1:i2);
}


int i1=15,i2=20;    


cout<<"Greater is "<<max(i1,i2) <<endl;   

long l1=40000, l2=38000;   

cout<<"Greater is "<<max(l1,l2) <<endl;    


float f1=55.05, f2=67.777;    


cout<<"Greater is "<<max(f1,f2) <<endl;    


char c1='a',c2='A';    


cout<<"Greater is "<<max(c1,c2) <<endl;    


getch();


}


int max(int i1, int i2)


{  


long max(long l1, long l2)


{  


return(l1>l2?l1:l2);


}


float max(float f1, float f2)


{  


return(f1>f2?f1:f2);


}


char max(char c1, char c2)


{  


return(c1>c2?c1:c2);


}

Passing by references in C++ Programming

         We can pass parameters in function in C++ by reference. When we pass arguments by reference, the  formal arguments in the called function become aliases to the  actual arguments in the calling  function i.e. when the function is working with its own arguments, it is actually working on the original data.

Example
 void fun (int &a) //a is reference variable { a=a+10; } 

int main()
{
int x=100;//CALL
cout< //a is reference variable{a=a+10;}int main(){ int x=100;fun(x);  //CALL cout< 

//prints 110

when function call fun(x) is executed, the following initialization occurs:  int &a=x; i.e. a is an alias for x and represents the same data in memory. So updating in function causes the update of the data represented by x. this type of function call is known as Call by reference.


 //pass by reference


#include<iostream.h>


#include<conio.h>
void swap(int &, int &);
 void main() {  int a=5,b=9;
cout<<"Before Swapping: a="<
swap(a,b);//call by reference

cout<<"After Swapping: a="<
getch(); }

 void swap(int &x, int &y)
{
int temp;
temp=x;
x=y;     

y=temp;
}


Return by reference 

       A function can return a value by reference. This is a unique feature of C++. Normally function is invoked only on the righthand side of the equal sign. But we can use it on the left side of equal sign and the value returned is put on the right side.  



//returning by reference from a function as a parameter 

#include<iostream.h>
int x=5,y=15;//globel variable
int &setx();
void main()
{
setx()=y;    //assign value of y to the variable    //returned by the function
cout<<"x="<


getch();
}
int &setx() {    //display global value of x   


cout<<"x="<

return x;

Default Arguments

In C++ a function can be called without specifying all its arguments. In such cases, the function assigns a default value to the parameter which does not have a matching argument in the function call. The default value is specified when function is declared. 
           The default value is specified like the variable initialization. The prototype for the declaration of default value of an argument looks like float amount (float p, int time, float rate=0.10);
// declares a default value of 0.10 to the argument rate.

The call of this function as
value = amount (4000,5) ;// one argument missing for rate passes the value 4000 top, 5 to time and the function looks the prototype for missing argument that is declared as default value 0.10 the function uses the default value 0.10 for the third argument. But the call

value = amount (4000,5,0.15);
 no argument is missing, in this case function uses this value 0.15 for rate.
 Note : only the trailing arguments can have default value. We must add default from right to left. E.g.
int add( int  a,  int b =9, int  c= 10 );  // legal
int add(int a=8, int b, int c); // illegal
int add(int a, int b = 9, int c);  //illegal
int add( int a=8, int b=9,int c=10) // legal

Types of default arguments: -


Automatic
External
Static
Register
Mutable
Lifetime
Within function
Throughout the program
Throughout program
Within function
Apply only for object
Visibility
Within function








 Scope of variables: -
-          Local
-          Global
-          Class

o   Storage class

Storage class defines the variable visibility and lifetime.

//default arguments in function //define default values for arguments that are not passed when

//a function call is made

#include<iostream.h>

void marks_tot(int m1=40,int m2=40, int m3=40 );

void main()

{

//imagine 40 is given if absent in exam.

marks_tot();

marks_tot(55);

marks_tot(66,77);

marks_tot(75,85,92);

getch(); }

void marks_

tot(int m1, int m2, int m3)

{

cout<<"Total marks"<<(m1+m2+m3)< 

}

Const Arguments 

When arguments are passed by reference to the function, the function can modify the variables in the calling program. Using the constant arguments in the function, the variables in the calling program cannot be modified. const qualifier is used for it.  e.g.
 
#include<iostream.h>void func(int&,const int&);
void  main()
{ int a=10, b=20;
func(a,b);
}
void func(int& x, int &y)
{
x=100;  y=200; // error  since y is constant argument
}


Reference Variables:

             C++ Programming introduces a new kind of variable known as reference variable. A reference variable provides an alias (Alternative name) of the variable that is previously defined. For example, if we make the variable sum a reference to the variable total, the sum and total can be used interchangeably to represent that variable.
 Syntax for defining reference variable
Data_type & reference_name = variable_nane
 

Example:
int total=100 ;
int &sum=total;


              Here total is int variable already declared. Sum is the alias for variable total. Both the variable refer to the same data 100 in the memory.


 cout< <total;  

and 

cout<<sum; gives the same output 100.
 And total= total+100;
 Cout< <sum;    //gives output 200

                

A reference variable must be initialized at the time of declaration. This establishes the correspondence between the reference and the data object which it means. The initialization of reference variable is completely different from assignment to it. A major application of the reference variables is in passing arguments to function.
 

//An example of reference

#include<iostream.h>
#include<conio.h>
 void main()
{
int x=5;
int &y=x;     //y is alias of x     

cout< <"x="< <x< <"and y="< <y< <endl;
 y++;     //y is reference of x;
cout< <"x="< <x< <"and y="< <y< <endl;
 getch();

}

Scope Resolution Operator( :: ) | C++ Programming

C++ programming supports a mechanism to access a global variable from a function in which a local variable is defined with the same name as a global variable. It is achieved using the scope resolution operator ::  

Global Variable Name

            The global variable to be accessed must be preceded by the scope resolution operator. It directs the compiler to access a global variable, instead of one defined as a local variable. The scope resolution operator permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same name in the local scope.

//An example of use of scoperesolution operator ::


#include&lt;iostream.h&gt;
#include&lt;conio.h&gt;
int x=5; void main()
{
int x=15;
cout&lt; &lt;"Local data x="&lt; &lt;x&lt; &lt;"Global data x="&lt; &lt;::x&lt; &lt;endl;
{
 int x=25; 
cout&lt; &lt;"Local data x="&lt; &lt;x&lt; &lt;"Global data x="&lt; &lt;::x&lt; &lt;endl;
}
 cout&lt; &lt;"Local data x="&lt; &lt;x&lt; &lt;"Global data x="&lt; &lt;::x&lt; &lt;endl;
 cout&lt; &lt;”Global +Local=”&lt; &lt;::x +x;
    getch();
}

Advantages and Disadvantages of OOP

Advantages of OOPs

Object oriented programming contributes greater programmer productivity, better quality of software and lesser maintenance cost. 

The main advantages are:

  1. Making the use of inheritance, redundant code is eliminated, and the existing class is extended.
  2. Through data hiding, programmer can build secure programs that cannot be invaded by code in other parts of the program.
  3. It is possible to have multiple instances of an object to co-exist without any interference.
  4. System can be easily upgraded from small to large systems.
  5. Software complexity can be easily managed.
  6. Message passing technique for communication between objects makes the interface description with external system much simpler.
  7. Aids trapping in an existing pattern of human thought into programming.
  8. Code reusability is much easier than conventional programming languages.


Disadvantages of OOPs

  1. Compiler and runtime overhead. Object oriented program required greater processing overhead – demands more resources.
  2. An object’s natural environment is in RAM as a dynamic entity but traditional data storage in files or databases.
  3. Re-orientation of software developer to object-oriented thinking.
  4. Requires the mastery in software engineering and programming methodology.
  5. Benefits only in long run while managing large software projects.
  6. The message passing between many objects in a complex application can be difficult to trace & debug.

Object Oriented Approach | C++ Programming

                The fundamental idea behind object-oriented language is to combine both data & function that separate data into a single unit such a unit is called object. A objects function called member function provides the way to access objects data.

The data item in an object can be access only by calling member function in object & data item cannot be accessed directly.


The data is hidden and safe from accidental alteration. In order to modify the data, we should know exactly what function interact with it, no other function can access the data.
               
Hence OOP focuses on data rather than algorithm for solving problems.

In other words, OOP is the method of implementation which program are organized as cp-operative collection of object.

A program in OOP consists several objects which communicate with each other by calling an object member function calling an object.
Object Oriented Approach


Figure: - Program Organization in OOP



In addition, OOP supports encapsulation, inheritance & polymorphism.
Ex: - simula, small talk, C++, Java, python, C#.


 IN OOP



  • ·         Emphasis is given on data rather than procedure.
  • ·         Problem are divided into objects
  • ·         Data structures are designed such that they characterize the objects.
  • ·         Functions and data are ties together in the data structures so that data       obstruction is introduced in addition to procedural abstraction.
  • ·         Data is hidden and cannot be accessed by external functions/
  • ·         Object communicate with each other through function
  • ·         New data and functions can be easily added.
  • ·         Follow the bottom-up approach of programming.

Elements/ Features of OOP: -



  • ·         Class
  • ·         Object
  • ·         Encapsulation
  • ·         Abstraction
  • ·         Inheritance
  • ·         Polymorphism
  • ·         Message Passing

Procedural Oriented Approach | C++ Programming

In procedural oriented approach programs are organized in form of subroutines. The subroutines do not let the code duplication. P.O. is suitable for medium sized software C, Pascal, FORTRAN etc. Are procedural oriented language.
               
            A program in a PL is a list is a list of instruction that tells the computer to do something. Such as get some input add these number, divide by 5 display output.
               
            The primary focus of POL is on function rather than data.
                
             The idea of breaking program into function can be entered by grouping a no of functions together into a larger entity called module.



Procedural Oriented Approach
Fig: Typical program structure in procedural programming

Problem with SP

                As program grow ever larger and more complex even the structured programming approach begins to show signs of strain. No matter how well the SP is implemented large programs become excessively complex causing to sleep the schedule extra programmer need to be added increasing project cost.
                The two reasons for these problem with P.A are: -
1.       First functions have unrestricted access to global data
2.       Second, unrelated functions and data the basis of procedural paradigm, provide a poor model of the real world.

Unrestricted Access: -

                A program in P.A use two kinds of data.
  • 1.       Local Data
  • 2.       Global Data


When two or more functions have to access the same data the data must be declared global. Global data can be access by any functions in the program.
        
         The arrangement of global data and local data of the program in P.A.
Procedural Oriented Approach





When there are many function and many global data item in a program there be difficulties to established a connection between the functions. & data finally lead large number of problems such as:
  • 1.       It makes a program structure difficult to conceptualized.
  • 2.       It makes program difficult to modify.
  • 3.       As single change in a global data item main associated rewriting all the functions that access that global items.


Real World Modeling: -

                The second and more important problem with P.P is that its arrangement of separate data and functions does a poor job of modelling things in the real world.
                In real world we deal with objects such as people, car etc. and such objects aren’t like the data and they aren’t like function. These object have both attributes and behavior.
                To model such objects, we need both data and fi=unction that operate a data on a single unit that is not separate individuals.
Procedural Oriented Approach

Characteristics of P.A: -

  • 1.       Emphasis is on doing thing(algorithm)
  • 2.       Large program is divided into smaller programs (function)
  • 3.       Most of the function share global data.
  • 4.       Data move freely or openly around system from function to function.
  • 5.       Function transform the data from one form to another.
  • 6.       Top down approach of program



Limitation of P.A

  • 1.       To revise external data structure all, the function that access data should be revised.
  • 2.       Focuses on function rather than data.
  • 3.    It doesn’t model real world problem very well since function are action oriented and don’t          really correspond to element of problems.