SlideShare una empresa de Scribd logo
1 de 25
FUNCTIONS IN C++
9/22/2017By MRI 1
Functions in C++
Functions are used to provide modularity to a
program. Creating an application using function
makes it easier to understand, edit, check errors
etc.
Functions allow to structure programs in segments
of code to perform individual tasks.
In C++, a function is a group of statements that is
given a name, and which can be called from some
point of the program.
9/22/2017By MRI 2
Functions in C++
Depending on whether a function is predefined or
created by programmer; there are two types of
function:
1. Library Function
2. User-defined Function
9/22/2017By MRI 3
User Defined Functions in C++
Syntax of Function
return-type function-name (parameters)
{
// function-body
}
return-type : suggests what the function will return. It can be int,
char, some pointer or even a class object. There can be functions
which does not return anything, they are mentioned with void.
Function Name : is the name of the function, using the function
name it is called.
Parameters : are variables to hold values of arguments passed
while function is called. A function may or may not contain
parameter list.
9/22/2017By MRI 4
Function prototype (declaration)
If a user-defined function is defined after main()
function, compiler will show error.
It is because compiler is unaware of user-defined
function, types of argument passed to function and
return type.
In C++, function prototype is a declaration of
function without its body to give compiler
information about user-defined function.
9/22/2017By MRI 5
Declaring, Defining and Calling Function
#include < iostream>
using namespace std;
int sum (int x, int y); //declaring function
int main()
{
int a = 10;
int b = 20;
int c = sum (a, b); //calling function
cout << c;
}
int sum (int x, int y) //defining function
{
return (X + y);
}
9/22/2017By MRI 6
Declaring, Defining and Calling Function
Here, initially the function is declared, without body.
Then inside main() function it is called, as the function
returns summation of two values, hence c is their to
store the value of sum.
Then, at last, function is defined, where the body of
function is mentioned. We can also, declare & define the
function together, but then it should be done before it is
called.
9/22/2017By MRI 7
Calling a Function
Functions are called by their names. If the function is
without argument, it can be called directly using its
name. But for functions with arguments, we have two
ways to call them:
1. Call by Value
2. Call by Reference
9/22/2017By MRI 8
Call by Value
In this calling technique we pass the values of
arguments which are stored or copied into the formal
parameters of functions. Hence, the original values are
unchanged only the parameters inside function changes.
void calc(int x);
int main()
{
int x = 10;
calc(x);
printf("%d", x);
}
void calc(int x)
{
x = x + 10 ;
}
Output : 10 9/22/2017By MRI 9
Call by Value
In this case the actual variable x is not changed,
because we pass argument by value, hence a
copy of x is passed, which is changed, and that
copied value is destroyed as the function
ends(goes out of scope).
So the variable x inside main() still has a value 10.
9/22/2017By MRI 10
Call by Value
But we can change this program to modify the
original x, by making the function calc() return a
value, and storing that value in x.
void calc(int x);
int main()
{
int x = 10;
calc(x);
printf("%d", x);
}
void calc(int x)
{
x = x + 10 ;
return x;
}
Output : 20 9/22/2017By MRI 11
Call by Reference
In this we pass the address of the variable as arguments. In this
case the formal parameter can be taken as a reference or a pointer,
in both the case they will change the values of the original
variable.
void calc(int *p);
int main()
{
int x = 10;
calc(&x); // passing address of x as argument
printf("%d", x);
}
void calc(int *p)
{
*p = *p + 10;
}
Output : 20
9/22/2017By MRI 12
Types of User-defined Functions in C++
9/22/2017By MRI 13
9/22/2017By MRI 14
Example 1: No arguments passed and no return value
# include <iostream>
using namespace std;
void prime();
int main()
{
prime(); // No argument is passed to prime()
return 0;
}
// Return type of function is void because value is not returned.
void prime()
{
int num, i, flag = 0;
cout << "Enter a positive integer enter to check: ";
cin >> num;
for(i = 2; i <= num/2; ++i)
{
if(num % i == 0)
{
flag = 1;
break;
}
}
if (flag == 1)
{
cout << num << " is not a prime number.";
}
else { cout << num << " is a prime number."; .
}
Inline function
Calling a function generally causes a certain
overhead (stacking arguments, jumps, etc...),
and thus for very short functions, it may be more
efficient to simply insert the code of the function
where it is called, instead of performing the
process of formally calling a function.
9/22/2017By MRI 15
Inline function
Preceding a function declaration with the inline
specifier informs the compiler that inline
expansion is preferred over the usual function
call mechanism for a specific function.
This does not change at all the behavior of a
function, but is merely used to suggest the
compiler that the code generated by the function
body shall be inserted at each point the function
is called, instead of being invoked with a regular
function call.
9/22/2017By MRI 16
Inline function
C++ inline function is powerful concept that is
commonly used with classes. If a function is
inline, the compiler places a copy of the code of
that function at each point where the function is
called at compile time.
To inline a function, place the
keyword inline before the function name and
define the function before any calls are made to
the function.
The compiler can ignore the inline qualifier in case
defined function is more than a line.
9/22/2017By MRI 17
Inline function
Following is an example, which makes use of
inline function to return max of two numbers:
#include <iostream>
using namespace std;
inline int Max(int x, int y)
{ return (x > y)? x : y; }
// Main function for the program
int main( ) {
cout << "Max (20,10): " << Max(20,10) << endl; cout <<
"Max (0,200): " << Max(0,200) << endl; cout << "Max
(100,1010): " << Max(100,1010) << endl; return 0;
}
9/22/2017By MRI 18
Friend function
A friend function of a class is defined outside that
class' scope 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.
A friend can be a function, function template, or
member function, or a class or class template, in
which case the entire class and all of its
members are friends.
9/22/2017By MRI 19
Friend function
To declare a function as a friend of a class,
precede the function prototype in the class
definition with keyword friend as follows:
class Box {
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};
9/22/2017By MRI 20
Friend function
#include <iostream>
using namespace std;
// forward declaration
class B;
class A
{
private:
int numA;
public:
A(): numA(12) { } // friend function declaration
friend int add(A, B);
};
class B {
private:
int numB;
public:
B(): numB(1) { } // friend function declaration
friend int add(A , B);
};
// Function add() is the friend function of classes A and B
// that accesses the member variables numA and numB
int add(A objectA, B objectB)
{
return (objectA.numA + objectB.numB);
}
int main()
{ A objectA;
B objectB;
cout<<"Sum: "<< add(objectA, objectB);
return 0;
}
9/22/2017By MRI 21
Friend function
In this program, classes A and B have declared
add() as a friend function.
Thus, this function can access private data of both
class.
Here, add() function adds the private data numA
and numB of two objects objectA and objectB, and
returns it to the main function.
To make this program work properly, a forward
declaration of a class class B should be made as
shown in the above example.
This is because class B is referenced within the
class A using code: friend int add(A , B);.
9/22/2017By MRI 22
Recursive function
A function that calls itself is known as recursive
function. And, this technique is known as
recursion.
void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
} 9/22/2017By MRI 23
9/22/2017By MRI 24
Examples of Recursive Function
// Factorial of n = 1*2*3*...*n
#include <iostream>
using namespace std;
int factorial(int);
int main()
{
int n;
cout<<"Enter a number to find factorial: ";
cin >> n;
cout << "Factorial of " << n <<" = " << factorial(n);
return 0;
}
int factorial(int n)
{
if (n > 1)
{
return n*factorial(n-1);
}
else
{
return 1;
}
}
9/22/2017By MRI 25

Más contenido relacionado

La actualidad más candente

Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
Kamal Acharya
 
Principles and advantages of oop ppt
Principles and advantages of oop pptPrinciples and advantages of oop ppt
Principles and advantages of oop ppt
daxesh chauhan
 
Data types in C language
Data types in C languageData types in C language
Data types in C language
kashyap399
 
constants, variables and datatypes in C
constants, variables and datatypes in Cconstants, variables and datatypes in C
constants, variables and datatypes in C
Sahithi Naraparaju
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 

La actualidad más candente (20)

Function in C program
Function in C programFunction in C program
Function in C program
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
functions of C++
functions of C++functions of C++
functions of C++
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 
Encapsulation C++
Encapsulation C++Encapsulation C++
Encapsulation C++
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Principles and advantages of oop ppt
Principles and advantages of oop pptPrinciples and advantages of oop ppt
Principles and advantages of oop ppt
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
 
Data types in C language
Data types in C languageData types in C language
Data types in C language
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
C functions
C functionsC functions
C functions
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++
 
constants, variables and datatypes in C
constants, variables and datatypes in Cconstants, variables and datatypes in C
constants, variables and datatypes in C
 
Inline function
Inline functionInline function
Inline function
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 

Similar a Functions in c++

Similar a Functions in c++ (20)

Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
unit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdfunit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdf
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
Unit 3 (1)
Unit 3 (1)Unit 3 (1)
Unit 3 (1)
 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptx
 
USER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdfUSER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdf
 
Unit 4.pdf
Unit 4.pdfUnit 4.pdf
Unit 4.pdf
 
Preprocessor directives
Preprocessor directivesPreprocessor directives
Preprocessor directives
 
Fundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programmingFundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programming
 
Function
FunctionFunction
Function
 
cp Module4(1)
cp Module4(1)cp Module4(1)
cp Module4(1)
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Chap 9(functions)
Chap 9(functions)Chap 9(functions)
Chap 9(functions)
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
 
Function in c
Function in cFunction in c
Function in c
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Unit iv functions
Unit  iv functionsUnit  iv functions
Unit iv functions
 

Más de Rokonuzzaman Rony (20)

Course outline for c programming
Course outline for c  programming Course outline for c  programming
Course outline for c programming
 
Pointer
PointerPointer
Pointer
 
Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
 
Constructors & Destructors
Constructors  & DestructorsConstructors  & Destructors
Constructors & Destructors
 
Classes and objects in c++
Classes and objects in c++Classes and objects in c++
Classes and objects in c++
 
Object Oriented Programming with C++
Object Oriented Programming with C++Object Oriented Programming with C++
Object Oriented Programming with C++
 
Humanitarian task and its importance
Humanitarian task and its importanceHumanitarian task and its importance
Humanitarian task and its importance
 
Structure
StructureStructure
Structure
 
Pointers
 Pointers Pointers
Pointers
 
Loops
LoopsLoops
Loops
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 
Array
ArrayArray
Array
 
Constants, Variables, and Data Types
Constants, Variables, and Data TypesConstants, Variables, and Data Types
Constants, Variables, and Data Types
 
C Programming language
C Programming languageC Programming language
C Programming language
 
User defined functions
User defined functionsUser defined functions
User defined functions
 
Numerical Method 2
Numerical Method 2Numerical Method 2
Numerical Method 2
 
Numerical Method
Numerical Method Numerical Method
Numerical Method
 
Data structures
Data structuresData structures
Data structures
 
Data structures
Data structures Data structures
Data structures
 
Data structures
Data structures Data structures
Data structures
 

Último

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Último (20)

HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
latest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answerslatest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answers
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 

Functions in c++

  • 2. Functions in C++ Functions are used to provide modularity to a program. Creating an application using function makes it easier to understand, edit, check errors etc. Functions allow to structure programs in segments of code to perform individual tasks. In C++, a function is a group of statements that is given a name, and which can be called from some point of the program. 9/22/2017By MRI 2
  • 3. Functions in C++ Depending on whether a function is predefined or created by programmer; there are two types of function: 1. Library Function 2. User-defined Function 9/22/2017By MRI 3
  • 4. User Defined Functions in C++ Syntax of Function return-type function-name (parameters) { // function-body } return-type : suggests what the function will return. It can be int, char, some pointer or even a class object. There can be functions which does not return anything, they are mentioned with void. Function Name : is the name of the function, using the function name it is called. Parameters : are variables to hold values of arguments passed while function is called. A function may or may not contain parameter list. 9/22/2017By MRI 4
  • 5. Function prototype (declaration) If a user-defined function is defined after main() function, compiler will show error. It is because compiler is unaware of user-defined function, types of argument passed to function and return type. In C++, function prototype is a declaration of function without its body to give compiler information about user-defined function. 9/22/2017By MRI 5
  • 6. Declaring, Defining and Calling Function #include < iostream> using namespace std; int sum (int x, int y); //declaring function int main() { int a = 10; int b = 20; int c = sum (a, b); //calling function cout << c; } int sum (int x, int y) //defining function { return (X + y); } 9/22/2017By MRI 6
  • 7. Declaring, Defining and Calling Function Here, initially the function is declared, without body. Then inside main() function it is called, as the function returns summation of two values, hence c is their to store the value of sum. Then, at last, function is defined, where the body of function is mentioned. We can also, declare & define the function together, but then it should be done before it is called. 9/22/2017By MRI 7
  • 8. Calling a Function Functions are called by their names. If the function is without argument, it can be called directly using its name. But for functions with arguments, we have two ways to call them: 1. Call by Value 2. Call by Reference 9/22/2017By MRI 8
  • 9. Call by Value In this calling technique we pass the values of arguments which are stored or copied into the formal parameters of functions. Hence, the original values are unchanged only the parameters inside function changes. void calc(int x); int main() { int x = 10; calc(x); printf("%d", x); } void calc(int x) { x = x + 10 ; } Output : 10 9/22/2017By MRI 9
  • 10. Call by Value In this case the actual variable x is not changed, because we pass argument by value, hence a copy of x is passed, which is changed, and that copied value is destroyed as the function ends(goes out of scope). So the variable x inside main() still has a value 10. 9/22/2017By MRI 10
  • 11. Call by Value But we can change this program to modify the original x, by making the function calc() return a value, and storing that value in x. void calc(int x); int main() { int x = 10; calc(x); printf("%d", x); } void calc(int x) { x = x + 10 ; return x; } Output : 20 9/22/2017By MRI 11
  • 12. Call by Reference In this we pass the address of the variable as arguments. In this case the formal parameter can be taken as a reference or a pointer, in both the case they will change the values of the original variable. void calc(int *p); int main() { int x = 10; calc(&x); // passing address of x as argument printf("%d", x); } void calc(int *p) { *p = *p + 10; } Output : 20 9/22/2017By MRI 12
  • 13. Types of User-defined Functions in C++ 9/22/2017By MRI 13
  • 14. 9/22/2017By MRI 14 Example 1: No arguments passed and no return value # include <iostream> using namespace std; void prime(); int main() { prime(); // No argument is passed to prime() return 0; } // Return type of function is void because value is not returned. void prime() { int num, i, flag = 0; cout << "Enter a positive integer enter to check: "; cin >> num; for(i = 2; i <= num/2; ++i) { if(num % i == 0) { flag = 1; break; } } if (flag == 1) { cout << num << " is not a prime number."; } else { cout << num << " is a prime number."; . }
  • 15. Inline function Calling a function generally causes a certain overhead (stacking arguments, jumps, etc...), and thus for very short functions, it may be more efficient to simply insert the code of the function where it is called, instead of performing the process of formally calling a function. 9/22/2017By MRI 15
  • 16. Inline function Preceding a function declaration with the inline specifier informs the compiler that inline expansion is preferred over the usual function call mechanism for a specific function. This does not change at all the behavior of a function, but is merely used to suggest the compiler that the code generated by the function body shall be inserted at each point the function is called, instead of being invoked with a regular function call. 9/22/2017By MRI 16
  • 17. Inline function C++ inline function is powerful concept that is commonly used with classes. If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time. To inline a function, place the keyword inline before the function name and define the function before any calls are made to the function. The compiler can ignore the inline qualifier in case defined function is more than a line. 9/22/2017By MRI 17
  • 18. Inline function Following is an example, which makes use of inline function to return max of two numbers: #include <iostream> using namespace std; inline int Max(int x, int y) { return (x > y)? x : y; } // Main function for the program int main( ) { cout << "Max (20,10): " << Max(20,10) << endl; cout << "Max (0,200): " << Max(0,200) << endl; cout << "Max (100,1010): " << Max(100,1010) << endl; return 0; } 9/22/2017By MRI 18
  • 19. Friend function A friend function of a class is defined outside that class' scope 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. A friend can be a function, function template, or member function, or a class or class template, in which case the entire class and all of its members are friends. 9/22/2017By MRI 19
  • 20. Friend function To declare a function as a friend of a class, precede the function prototype in the class definition with keyword friend as follows: class Box { double width; public: double length; friend void printWidth( Box box ); void setWidth( double wid ); }; 9/22/2017By MRI 20
  • 21. Friend function #include <iostream> using namespace std; // forward declaration class B; class A { private: int numA; public: A(): numA(12) { } // friend function declaration friend int add(A, B); }; class B { private: int numB; public: B(): numB(1) { } // friend function declaration friend int add(A , B); }; // Function add() is the friend function of classes A and B // that accesses the member variables numA and numB int add(A objectA, B objectB) { return (objectA.numA + objectB.numB); } int main() { A objectA; B objectB; cout<<"Sum: "<< add(objectA, objectB); return 0; } 9/22/2017By MRI 21
  • 22. Friend function In this program, classes A and B have declared add() as a friend function. Thus, this function can access private data of both class. Here, add() function adds the private data numA and numB of two objects objectA and objectB, and returns it to the main function. To make this program work properly, a forward declaration of a class class B should be made as shown in the above example. This is because class B is referenced within the class A using code: friend int add(A , B);. 9/22/2017By MRI 22
  • 23. Recursive function A function that calls itself is known as recursive function. And, this technique is known as recursion. void recurse() { ... .. ... recurse(); ... .. ... } int main() { ... .. ... recurse(); ... .. ... } 9/22/2017By MRI 23
  • 25. Examples of Recursive Function // Factorial of n = 1*2*3*...*n #include <iostream> using namespace std; int factorial(int); int main() { int n; cout<<"Enter a number to find factorial: "; cin >> n; cout << "Factorial of " << n <<" = " << factorial(n); return 0; } int factorial(int n) { if (n > 1) { return n*factorial(n-1); } else { return 1; } } 9/22/2017By MRI 25