You are on page 1of 33

C++ FUNCTIONS 1

BY MR. TARUS
Functions
Self contained block of statements which performs a particular task and
returns a value.

The function contains the set of programming statements enclosed by {}.

Collection of functions creates a C/C++ program i.e


C/C++ = main() + add() + sum() + ….. +last()

Function also called module, block, partition, procedure, subroutine

Every C++ program must have the main()


Check the role of main() [ 2 main / key roles ]
Importance of functions in a program

Facilitate code Re-use

Facilitate program expansion

Facilitate the location and isolation of faulty functions in a program

Facilitate top down programming


Types of functions
1. Library Functions: Functions which are declared
in the C++ header files such as ceil(x), cos(x),
exp(x), gets(), puts(), ceil(), floor(), sqrt(), pow()
etc.
Functions which have been coded, compiled and
utilized in other programs.
2. User-defined functions: Functions which are
created by the C++ programmer, so that he/she can
use it many times. It reduces the complexity of a
big program and optimizes the code.
Eg addition(), tarus(), a(), sum();
Communication in functions
Functions communicate by passing messages.

Three concepts in functions that are very important:


Function declaration
Function call
Function definition

User defined functions must be declared before they are used in the
program.
Program demo for functions in C++
/* functions demo program */
#include<stdio.h> void china() //function definition
void japan(); //function declaration
void china(); {

int main() cout<<“\n iam in china \n”;


{ }
cout<<“\n initially in main function\n”;
japan(); function call
void japan() //function definition
cout<<“\nfrom japan \n”;
china(); function call {
cout<<“\nfrom china \n”; cout“\n iam in japan \n”;
return 0; }
}
Concepts of functions
1. Function Declaration:
Done outside all other functions [ between header files and main() ]
Done inside the class to provide encapsulation.
Syntax:
return_type function_name(return_type1 arg1, ……);
E.g, int addition(int a, int b, int c); parameter /argument
Declaration informs the compiler about the following:
 Return type of the function
 Function name
 Return types of parameters in the argument list.
 Number of parameters in the argument list
Nb: Declaration creates a template / structure of the function. This structure will
be used to link the function call and function definition.
Function call, definition
• addition(a,b,c); call
• structure of function declaration

• void addition(int x, int y, int z) definition


#include<iostream.h>
#include<conio.h>   int sum(int x, int y)  
{  
int sum(int , int );  
int z;
int subtraction(int, int);
z = x + y;
int main()  
cout<<"\nThe sum is : ”<<z;
{  
    return 0;  
    int a, b, result;    
}  
    cout"\nEnter two numbers:";  
Int subtraction(int x, int y)
    cin>>a>>b;   {
    result = sum(a, b);   sub =x-y;
subtraction(a,b); return sub;
  return 0;     }
#include<iostream> 
int sum()  
#include<conio.h> 
{  
int sum();  
    int a,b;   
int main()       cout<<"\nEnter two numbers";  
{  
    int result;        cin>>a>>b;  
    result = sum();  
    return a+b;   
    cout<<“\n result = “<<result;
return 0;   }  
}  
Communication in functions: Cont’d…..
1. Pass by value

2. Pass by reference
Pass by value
Call/Pass by value is the process where the copies of the actual parameters
are passed in one to one correspondence to the formal parameters in the
function definition. Therefore, any changes made in the formal parameters do
not affect the actual parameters.
e.g, addition(int a, int b, int c); call
Copies
int addition(int x, int y, int z) definition

Nb: Variables a, b, c are called actual parameters

Variables x, y, z are called formal parameters


/* Pass by Value*/ int badilisha(int x, int y)
#include<iostream>
#include<conio.h> {
int badilisha(int, int); int z;
int main()
z = x;
{
int a=5, b=7; x = y;
cout<<"\nOriginal values\n"; y = z;
cout<<"\na = \t”<<a<<endl;
cout<<"b = \n”<<b; cout<<"\nValues in fun definiti\n";
badilisha(a,b); cout<<"\na = \t“<<x;
cout<<"\nValue after interchange\n";
cout<<"b = \n“<<y;
cout<<"\na = \t“<<a;
cout<<"b = \n“<<b<<endl; }
return 0;
}
Inline function
 Functions which are expanded with the keyword inline
 Syntax:
inline return_type function_name(parameters)  
{  
   // function code?  
}   
 Importance of inline functions:
to save memory space.
Increase the execution speed
Instances where inline functions may not work

 If a function is recursive.

 If a function contains a loop like for, while, do-while loop.

 If a function contains static variables.

 If a function contains a switch or go to statement


Advantages of inline function
 In the inline function, we do not need to call a function, so it does not cause any
overhead.

 It also saves the overhead of the return statement from a function.

 It does not require any stack on which we can push or pop the variables as it
does not perform any function calling.

 An inline function is mainly beneficial for the embedded systems as it yields


less code than a normal function.

 Nb: discuss the disadvantages of inline functions


Function overloading
 Feature that allows us to have more than one function having same name but
different parameter list
 Multiple functions can have the same name as long as the number and/or type of
parameters are different.
Advantages:
 It increases the readability of
the program because you don't need
to use different names for the same action.
 Types of overloading in C++ are:
 Function overloading
 Operator overloading
int mul(int,int); int main()
float mul(float,int); {
int mul(int a,int b) int r1 = mul(6,7);
{ float r2 = mul(0.2,3);
return a*b; cout<< "r1 is : " <<r1<<endl;
} cout<<"r2 is : " <<r2<<endl;
float mul(double x, int y) return 0;
{ }
return x*y;
}
Static Members of a C++ Class (static variables)

 Class members can be defined using static keyword.

 Static declaration of class members means no matter how many objects of the
class are created, there is only one copy of the static member.

 A static member is shared by all objects of the class.

 All static data is initialized to zero when the first object is created if no other
initialization is present.

 Can be initialized outside the class i.e, int Box::objectCount = 0;


Pto…
• Nb: By declaring a function member as static, you make it independent of any
particular object of the class i.e.,
Can be called/accessed even if no objects of the class exist.
Are accessed using only the class name and the scope resolution operator ::
StaticDemo2.cpp

• A static member function can only access static data member, other static
member functions and any other functions from outside the class.
• Static member functions have a class scope and they do not have access to
the this pointer of the class. You could use a static member function to
determine whether some objects of the class have been created or not.
//static data member private:
class Box { double length; double breadth; double
public: height;};
static int objectCount; // Initialize static member of class Box
int display(); int Box::objectCount = 0;
// Constructor definition int main(void) {
Box(double l, double b, double h) { Box Box1(3.3, 1.2, 1.5);
cout <<"Constructor called." << endl; Box Box2(8.5, 6.0, 2.0);
length = l; breadth = b; height = h; Box1.Volume();
// Increase every time object is created
Box2.Volume();
objectCount++;
// Print total number of objects.
}
cout<<"Tot object:"<<Box::objectCount;
double Volume() {
return 0;
cout<<"\n AREA = "<<(length*breadth*
height); }
Static Member Function
 Functions declared with the keyword static
 Function which can be called even if no objects of the class exist, therefore can be
accessed using only the class name and the scope resolution operator ::.
 Can only access static data member, other static member functions and any other
functions from outside the class.
 Have a class scope.
 Do not have access to the this pointer of the class.
 Used to determine whether some objects of the class have been created or not.
 Properties:
Can only access other static variables or functions present in the same class
Called using the class name. Syntax- class_name::function_name( )

 StaticDemo2.cpp
class Box {
int Box::objectCount = 0;
public:
int main() {
static int objectCount;
Box(double l, double b, double h) {
// Print total number of objects before
creating object.
cout<<"Constructor called."<<endl;
cout << "Inital Stage Count: "<<
length = l; breadth = b; height = h;
Box::getCount() << endl;
// Increase every time object is created
Box Box1(3.3, 1.2, 1.5);
objectCount++;
}
Box Box2(8.5, 6.0, 2.0);
double Volume() { Box1.Volume();
cout<<"\nAREA="<<(length*breadth*height); Box2.Volume();
} // Print total number of objects after
static int getCount() { creating object.
return objectCount; cout << "Final Stage Count: " <<
} Box::getCount() << endl;
private: return 0;
double length, breadth, height; }; }
Introduction to Friend Functions
 Data hiding is fundamental concept in OOP, i.e, data members declared in
private section of a class. This is to restrict access of data members from outside
the class.

 Protected members can only be accessed by the derived classes and are
inaccessible from outside the class.

 Consider: friendDemo.cpp
Friend Function: PTO…
 Functions that can access the private and protected data of a class.
 A function of the class defined outside the class scope but it has the right to
access all the private and protected members of the class.
 friend functions appear in the class definition but friends are the member
functions.
 Characteristics of a Friend function:
 The friend function is declared using friend keyword.
 It is not a member of the class but it is a friend of the class.
 As it is not a member of the class so it can be defined like a normal function.
 Friend functions do not access the class data members directly but they pass an
object as an argument.
• It is not in the scope of the class that declares it as a friend.
Reasons for using friend functions
 Used when the class private data needs to be accessed directly without using
object of that class.
 Used to perform operator overloading.

 Syntax:
class class_name      
{      
    friend data_type function_name(argument/s);                
};      
Function can be defined anywhere in the program like a normal C++
Function definition does not use either the keyword friend or :: operator
Preceded by the keyword friend.
Advantages of Friend Function in C++

 friendFunction.cpp, friendFunction1.cpp

 The friend function allows the programmer to generate more efficient codes.

 It allows the sharing of private class information by a non-member function.

 It accesses the non-public members of a class easily.

 It is widely used in cases when two or more classes contain the interrelated
members relative to other parts of the program.

  It allows additional functionality that is not used by the class commonly.
class Distance { Friend function program
private: void addvalue(Distance &d) // argument
int meters; contain the reference
{
public:
d.meters = d.meters+10; //
Distance() // constructor incrementing the value of meters by 10.
{ }
meters = 0; int main()
} {
void display_data() Distance d1;
{ d1.display_data(); // meters = 0
cout << "Meters value: "<<meters<<endl; addvalue(d1); // calling friend function
} d1.display_data(); // meters = 10
friend void addvalue(Distance &d); return 0;
}; }
Friend Class
 Assume that class B is the friend class of class A.

 Thus, class B has access to all the members of class A.

 Consider:
friendClass1.cpp
friendClass.cpp

Explanation:

 The function add() is created in class B. This function returns the sum of numA and
numB. It is easy to create objects of class A inside class B, as the latter is a friend
class.
Friend class program: friendClass.cpp
class A {
int x =5;
int main()
friend class B; // friend class.
{
};
A a;
class B
B b;
{
b.display(a);
public:
return 0;
void display(A &a)
}
{
cout<<"value of x is : "<<a.x;
}
};
C++ Math Functions

 Trignometric functions: (tan(x), acos(x), sin(x), cos(x))

 Hyperbolic functions: (cosh(x), sinh(x), tanh(x), acosh(x))

 Exponential functions: (exp(x), log10(x), log(x))

 Maximum, Minimum and Difference functions: (fdim(x,y), fmax(x,y), fmin())

 Power functions: (pow(x,y), sqrt(x), cbrt(x), hypot(x,y))

 mathematicalFun.cpp
Assignment

• Discuss by using relevant programming examples “operator


overloading”

You might also like