Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
70 views

Object Oriented Programming Lab 4

The document discusses functions in C++. It defines a function as a subprogram that acts on data and can return a value. It then discusses different types of functions including user-defined functions, functions with arguments, functions with return values, inline functions, and overloaded functions. Function overloading allows using the same function name for functions that perform the same operation but with different arguments.

Uploaded by

Haristic 01
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views

Object Oriented Programming Lab 4

The document discusses functions in C++. It defines a function as a subprogram that acts on data and can return a value. It then discusses different types of functions including user-defined functions, functions with arguments, functions with return values, inline functions, and overloaded functions. Function overloading allows using the same function name for functions that perform the same operation but with different arguments.

Uploaded by

Haristic 01
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

HITEC UNIVERSITY, TAXILA

FACULTY OF ELECTRICAL ENGINEERING

EE DEPARTMENT

Experiment # 04
Functions, Function overloading

Objective
The objective of this lab is to get the understanding of function, types of functions and define user
functions and return value from function

Software Tools
1. Microsoft Visual Studio

Theory
1. Function

A function is a subprogram that acts on data and often returns a value. A program written with
numerous functions is easier to maintain, update and debug than one very long program. By
programming in a modular (functional) fashion, several programmers can work independently on
separate functions which can be assembled at a later date to create the entire project. Each
function has its own name. When the function is finished, execution returns to the area of the
program code from which it was called, and the program continues on to the next line of code.

Steps for Creating user-defined functions

Declare the function


The declaration, called the FUNCTION PROTOTYPE, informs the compiler about the
functions to be used in a program, the argument they take and the type of value they return.

Define the function


The function definition tells the compiler what task the function will be performing. The function
prototype and the function definition must be same on the return type, the name, and the
parameters. The only difference between the function prototype and the function header is a
semicolon.
The function definition consists of the function header and its body. The header is EXACTLY
like the function prototype, EXCEPT that it contains NO terminating semicolon.

Object Oriented Programming 2nd Semester-EE HITEC University Taxila


HITEC UNIVERSITY, TAXILA
FACULTY OF ELECTRICAL ENGINEERING

EE DEPARTMENT

//Prototyping, defining and calling a function


#include <iostream>
using namespace std;
void starline(); // prototype the function
int main()
{
starline( ); // function call
cout<< "\t\tBjarne Stroustrup\n";
starline( ); // function call
return 0;
}

// function definition
void starline()
{
int count; // declaring a LOCAL variable
for(count = 1; count <=65; count++)
cout<< "*";
cout<<endl;
}

Argument to a function
Sometimes the calling function supplies some values to the called function. These are known as
parameters. The variables which supply the values to a calling function called actual parameters.
The variable which receive the value from called statement are termed formal parameters.

Consider the following example that evaluates the area of a circle.

#include<iostream>
using namespace std;
void area(float);
int main()
{
float radius;
cin>>radius;
area(radius);
return 0;

Object Oriented Programming 2nd Semester-EE HITEC University Taxila


HITEC UNIVERSITY, TAXILA
FACULTY OF ELECTRICAL ENGINEERING

EE DEPARTMENT

}
void area(float r)
{
cout<< “the area of the circle is”<<3.14*r*r<<”\n”;
}
Here radius is called actual parameter and r is called formal parameter.

Return type of a function


// Example program
#include <iostream>
using namespace std;

int timesTwo(int num); // function prototype


int main()
{
int number, response;
cout<<"Please enter a number:";
cin>>number;
response = timesTwo(number); //function call
cout<< "The answer is "<<response;
return 0;
}

//timesTwo function
int timesTwo (int num)
{
int answer; //local variable
answer = 2 * num;
return (answer);
}

Calling of a function
The function can be called using either of the following methods:
i) call by value
ii) call by reference

Call by value
In call by value method, the called function creates its own copies of original values sent to it.
Any changes, that are made, occur on the function’s copy of values and are not reflected back to
the calling function.

Object Oriented Programming 2nd Semester-EE HITEC University Taxila


HITEC UNIVERSITY, TAXILA
FACULTY OF ELECTRICAL ENGINEERING

EE DEPARTMENT

Call by reference
In call be reference method, the called function accesses and works with the original values using
their references. Any changes, that occur, take place on the original values are reflected back to
the calling code.
Consider the following program which will swap the value of two variables.

using call by reference using call by value

#include<iostream> #include<iostream>
using namespace std; using namespace std;
void swap(int &, int &); void swap(int , int );
int main() int main()
{ {
int a=10,b=20; int a=10,b=20;
swap(a,b); swap(a,b);
cout<<a<<" "<<b; cout<<a<<" "<< b;
return 0; return 0;
} }
void swap(int &c, int &d) void swap(int c, int d)
{ {
int t; int t;
t=c; t=c;
c=d; c=d;
d=t; d=t;
} }

output: output:
20 10 10 20

Function with default arguments


C++ allows to call a function without specifying all its arguments. In such cases, the function
assigns a default value to a parameter which does not have a mathching arguments in the function
call. Default values are specified when the function is declared. The complier knows from the
prototype how many arguments a function uses for calling.
Example
float result(int marks1, int marks2, int marks3=75);
a subsequent function call

Object Oriented Programming 2nd Semester-EE HITEC University Taxila


HITEC UNIVERSITY, TAXILA
FACULTY OF ELECTRICAL ENGINEERING

EE DEPARTMENT

average = result(60,70);
passes the value 60 to marks1, 70 to marks2 and lets the function use default value of 75 for
marks3.
The function call
average = result(60,70,80);
passes the value 80 to marks3.

Inline function
Functions save memory space because all the calls to the function cause the same code to be
executed. The functions body need not be duplicated in memory. When the complier sees a
function call, it normally jumps to the function. At the end of the function, it normally jumps back
to the statement following the call.
While the sequence of events may save memory space, it takes some extra time. To save
execution time in short functions, inline function is used. Each time there is a function call, the
actual code from the function is inserted instead of a jump to the function. The inline function is
used only for shorter code.
inline int cube(int r)
{
return r*r*r;
}
Some important points to be noted
 Function is made inline by putting a word inline in the beginning.
 Inline function should be declared before main() function.
 It does not have function prototype.
 Only shorter code is used in inline function. If longer code is made inline then compiler ignores
the request and it will be executed as normal function.

Global variable and local variable


Local Variable: A variable declared within the body of a function will be evaluated only within
the function. The portion of the program in which a variable is retained in memory is known as
the scope of the variable. The scope of the local variable is a function where it is defined. A
variable may be local to function or compound statement.
Global variable: A variable that is declared outside any function is known as a global variable.
The scope of such a variable extends till the end of the program. These variables are available to

Object Oriented Programming 2nd Semester-EE HITEC University Taxila


HITEC UNIVERSITY, TAXILA
FACULTY OF ELECTRICAL ENGINEERING

EE DEPARTMENT

all functions which follow their declaration. So it should be defined at the beginning, before any
function is defined.
Unary scope resolution operator (::) It is possible to declare local and global variables of the
same name. C++ provides the unary scope resolution operator (::) to access a global variable
when a local variable of the same name is in scope. A global variable can be accessed directly
without the unary scope resolution operator if the name of the global variable is not the same as
that of a local variable in scope.

2. Function overloading
Function overloading allows you to use the same name for different functions.Function
overloading is usually used to enhance the readability of the program. If you have to perform one
single operation but with different number or types of arguments, then you can simply overload
the function.
Ways to overload a function
1. By changing number of Arguments.
2. By having different types of argument.

Different number of arguments


In this type of function overloading, we define two functions with same names but different
number of parameters of the same type. For example, in the below mentioned program we have
made two sum() functions to return sum of two and three integers.
int sum (int x, int y)
{
cout << x+y;
}

int sum(int x, int y, int z)


{
cout << x+y+z;
}
Here sum() function is overloaded, to have two and three arguments. Which sum() function will
be called, depends on the number of arguments.
int main()
{
sum (10,20); // sum() with 2 parameter will be called

sum(10,20,30); //sum() with 3 parameter will be called


}
Object Oriented Programming 2nd Semester-EE HITEC University Taxila
HITEC UNIVERSITY, TAXILA
FACULTY OF ELECTRICAL ENGINEERING

EE DEPARTMENT

Different data type of arguments


In this type of overloading, we define two or more functions with same name and same number of
parameters, but the type of parameter is different. For example in this program, we have two
sum() function, first one gets two integer arguments and second one gets two double arguments.
int sum(int x,int y)
{
cout<< x+y;
}

double sum(double x,double y)


{
cout << x+y;
}

int main()
{
sum (10,20);
sum(10.5,20.5);
}

Object Oriented Programming 2nd Semester-EE HITEC University Taxila


HITEC UNIVERSITY, TAXILA
FACULTY OF ELECTRICAL ENGINEERING

EE DEPARTMENT

Lab Tasks

1. Write a function that takes two integers and returns the larger one.
2. Write a function that takes username and password as string and display message "login in
success" if username is "abcd" and password is="pakistan" and display message "Login
failed" otherwise.
3. Write a function that swaps two numbers void swap() using reference parameters. Swap
two numbers without using third variable.
4. Write a C++ program with a function int find_char(char*,char)
That finds out whether there is a given character in a string. The return value of the
function find_char() should be 1 if the given character is in the string otherwise 0.
5. Write a function to add 10 in each element of an array.
6. Overload the function in Question 1 with Different number of arguments.
7. Overload the function in Question 3 with Different data types of arguments.

Object Oriented Programming 2nd Semester-EE HITEC University Taxila

You might also like