SlideShare a Scribd company logo
4
Most read
6
Most read
8
Most read
1
Functions in C++
Ahmad Baryal
Saba Institute of Higher Education
Computer Science Faculty
Oct 21, 2024
2 Table of contents
 What is function?
 Why do we need functions?
 Function structure
 Function declaration
 Types of functions
 Function calling
 Function call methods
 Recursion
 Inline Functions
 Function overloading
3 Function C++
 A function is a set of statements that takes input, does some specific
computation, and produces output. The idea is to put some commonly or
repeatedly done tasks together to make a function so that instead of writing the
same code again and again for different inputs, we can call this function.
 They also enable code reusability by allowing you to call a function multiple times
within your program.
4 Why Do we Need Functions?
• Functions help us in reducing code redundancy. If functionality is performed
at multiple places in software, then rather than writing the same code,
again and again, we create a function and call it everywhere. This also
helps in maintenance as we have to make changes in only one place if
we make changes to the functionality in future.
• Functions make code modular. Consider a big file having many lines of
code. It becomes really simple to read and use the code, if the code is
divided into functions.
• Functions provide abstraction. For example, we can use library functions
without worrying about their internal work.
5 Function structure in c++
Let's break down the components of a C++ function:
return_type: This is the data type of the value that the function will return after it has
executed its task. If the function doesn't return a value, you can use void as the return
type.
function_name: This is the name you choose for your function, following the naming rules
of C++.
parameters: These are optional input values that the function can accept. Parameters
are enclosed in parentheses and separated by commas. They allow you to pass
information into the function for processing.
Function body: This is the actual code that performs the specific task of the function.
return (optional): If the return_type is not void, you can use the return statement to send a
6 Function Return Type in C++
The return type is the type of value returned by the function. A function in C++ may or may
not return a value. If the function does not return a value then its return type is void. Value
is returned from a function using the return statement. Control is transferred back to the
caller when the return statement is executed. If the function returns a value then we need
to specify its data type, like int, char, or float.
Note: Only one value can be returned from a function in C++. It is mandatory to return a
value for functions with a non-void return type.
For example, consider a function calculateFactorial which calculates the factorial of a
number and returns an integer value. We can see its return type is int.
int calculateFactorial( int num)
{
int fact=1;
for(int i=1;i<=num;i++)
fact*=i;
return fact; }
7 Types of Functions
1. User Defined Function are user/customer-defined blocks of code specially
customized to reduce the complexity of big programs. They are also commonly
known as “tailor-made functions” which are built only to satisfy the condition in
which the user is facing issues meanwhile reducing the complexity of the whole
program.
2. Library functions are also called “built-in Functions“. These functions are part of a
compiler package that is already defined and consists of a special function with
special and different meanings. Built-in Function gives us an edge as we can directly
use them without defining them whereas in the user-defined function we have to
declare and define a function before using them.
For Example: sqrt(), sort(),pow(),reverse(),abs(), etc.
8 Calling a Function
In C++, you can call a function by specifying the function's name, followed by
parentheses containing any necessary arguments (if the function takes parameters).
Here's the basic syntax for calling a function in C++:
// Function declaration
int add(int a, int b);
int main() {
int result = add(5, 3); // Calling the add function
cout << "Result: " << result << endl;
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
9 There are two most popular ways to pass parameters:
1. Pass by Value: In this parameter passing method, values of actual parameters are
copied to the function’s formal parameters. The actual and formal parameters are
stored in different memory locations so any changes made in the functions are not
reflected in the actual parameters of the caller.
void incrementByValue(int x) {
x++; // Increment the value of x
cout << "Inside incrementByValue: x = " << x << endl;
}
int main() {
int num = 5;
cout << "Original value of num: " << num << endl;
incrementByValue(num);
cout << "After incrementByValue: num = " << num << endl;
return 0;
}
10 There are two most popular ways to pass parameters:
1. Pass by Reference: Both actual and formal parameters refer to the same locations, so
any changes made inside the function are reflected in the actual parameters of the
caller.
void incrementByReference(int &x) {
x++; // Increment the value referred to by x
cout << "Inside incrementByReference: x = " << x << endl;
}
int main() {
int num = 5;
cout << "Original value of num: " << num << endl;
incrementByReference(num);
cout << "After incrementByReference: num = " << num << endl;
return 0;
}
11
Difference between call by value and call by reference in C++
Call by value
 A copy of the value is passed to
the function
 Changes made inside the
function are not reflected on
other functions
 Actual and formal arguments will
be created at different memory
location
Call by reference
 An address of value is passed to
the function
 Changes made inside the
function are reflected outside the
function as well
 Actual and formal arguments will
be created at same memory
location.
12 Recursion in function
Recursion is a programming concept where a function calls itself directly or indirectly to
solve a problem.
#include <iostream>
using namespace std;
// Recursive factorial function
int factorial(int n) {
// Base case: factorial of 0 is 1
if (n == 0 || n == 1) {
return 1;
} else {
// Recursive case: n! = n * (n-1)!
return n * factorial(n - 1);
}
}
int main() {
// Example usage of the factorial function
int num = 5;
cout << "Factorial of " << num << " is: " << factorial(num) << endl;
return 0;
}
13 Inline functions
Inline functions in C++ are expanded by the compiler directly at the point of the
function call, eliminating the overhead of a regular function call.
Marked with the inline keyword.
Pros:
• Performance improvement by reducing function call overhead.
• Compiler optimization opportunities.
• Reduced time and space overhead on the call stack.
Cons:
• Potential code bloat due to duplicated code at call sites.
• Compiler might choose not to inline based on its optimization criteria.
• Can reduce code maintainability for complex functions.
14 Inline functions Example
#include <iostream>
using namespace std;
// Definition of an inline function
inline int square(int x) {
return x * x;
}
int main() {
int num = 5;
// Inline function call
int result = square(num);
cout << "Square of " << num << " is: " << result << endl;
return 0; }
15 Function overloading
• Function overloading is a feature in C++ that allows multiple functions in the same scope with
the same name but different parameter lists.
• It provides a way to create functions that perform similar tasks but with variations in the type or
number of parameters.
Overloading Based on the Number and Type of Parameters:
• Overloaded functions must differ in either the number or type of their parameters.
• The compiler determines which function to call based on the number and types of arguments
passed during the function call.
16 Example 1: Overloading Based on Number of Parameters:
#include <iostream>
using namespace std;
// Function to add two integers
int add(int a, int b) {
return a + b;
}
// Overloaded function to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
int main() {
cout << "Sum of 2 and 3: " << add(2, 3) << endl;
cout << "Sum of 2, 3, and 4: " << add(2, 3, 4) << endl;
return 0;
}
17 Example 2: Overloading Based on Type of Parameters:
#include <iostream>
using namespace std;
// Function to add two integers
int add(int a, int b) {
return a + b;
}
// Overloaded function to concatenate two strings
string add(const string& str1, const string& str2) {
return str1 + str2;
}
int main() {
cout << "Sum of 2 and 3: " << add(2, 3) << endl;
cout << "Concatenation of 'Hello' and ' World': " << add("Hello", " World") <<
endl;
return 0;
}
18 Functions Using Pointers
The function fun() expects a pointer ptr to an integer (or an address of an
integer). It modifies the value at the address ptr. The dereference operator * is
used to access the value at an address. In the statement ‘*ptr = 30’, the value
at address ptr is changed to 30. The address operator & is used to get the
address of a variable of any data type. In the function call statement ‘fun(&x)’,
the address of x is passed so that x can be modified using its address.
// C++ Program to demonstrate working of
// function using pointers
#include <iostream>
using namespace std;
void fun(int* ptr) { *ptr = 30; }
int main()
{
int x = 20;
fun(&x);
cout << "x = " << x;
return 0;
19
Any Questions?

More Related Content

PDF
Chap 5 c++
Venkateswarlu Vuggam
 
PPTX
Fundamental of programming Fundamental of programming
LidetAdmassu
 
PPT
Chap 5 c++
Venkateswarlu Vuggam
 
PPTX
Chapter 1 (2) array and structure r.pptx
abenezertekalign118
 
PPTX
Silde of the cse fundamentals a deep analysis
Rayhan331
 
DOCX
Function Overloading,Inline Function and Recursion in C++ By Faisal Shahzad
Faisal Shehzad
 
PPTX
Functions in C++ programming language.pptx
rebin5725
 
PPTX
CHAPTER THREE FUNCTION.pptx
GebruGetachew2
 
Fundamental of programming Fundamental of programming
LidetAdmassu
 
Chapter 1 (2) array and structure r.pptx
abenezertekalign118
 
Silde of the cse fundamentals a deep analysis
Rayhan331
 
Function Overloading,Inline Function and Recursion in C++ By Faisal Shahzad
Faisal Shehzad
 
Functions in C++ programming language.pptx
rebin5725
 
CHAPTER THREE FUNCTION.pptx
GebruGetachew2
 

Similar to 6. Functions in C ++ programming object oriented programming (20)

PPT
16717 functions in C++
LPU
 
PPTX
unit_2.pptx
Venkatesh Goud
 
PPT
C++ Functions.ppt
WaheedAnwar20
 
PPT
C++ functions
Dawood Jutt
 
PPT
C++ functions
Dawood Jutt
 
PDF
unit3 part2 pcds function notes.pdf
JAVVAJI VENKATA RAO
 
PPT
Lecture 4
Mohammed Saleh
 
PPTX
Inline function
Tech_MX
 
PDF
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
jacobdiriba
 
PPTX
Unit-III.pptx
Mehul Desai
 
PPT
arrays.ppt
Bharath904863
 
PDF
Functions in C++.pdf
LadallaRajKumar
 
PDF
PSPC-UNIT-4.pdf
ArshiniGubbala3
 
PPTX
Functions in c++
Rokonuzzaman Rony
 
PPTX
functIONS PROGRAMMING CIII II DJDJKASDJKJASD.pptx
nandemprasanna
 
PPT
C++ Functions.ppt
kanaka vardhini
 
PPT
power point presentation on object oriented programming functions concepts
bhargavi804095
 
PPTX
Chp8_C++_Functions_Part2_User-defined functions.pptx
ssuser10ed71
 
PPTX
Functions
Golda Margret Sheeba J
 
PPT
Unit iv functions
indra Kishor
 
16717 functions in C++
LPU
 
unit_2.pptx
Venkatesh Goud
 
C++ Functions.ppt
WaheedAnwar20
 
C++ functions
Dawood Jutt
 
C++ functions
Dawood Jutt
 
unit3 part2 pcds function notes.pdf
JAVVAJI VENKATA RAO
 
Lecture 4
Mohammed Saleh
 
Inline function
Tech_MX
 
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
jacobdiriba
 
Unit-III.pptx
Mehul Desai
 
arrays.ppt
Bharath904863
 
Functions in C++.pdf
LadallaRajKumar
 
PSPC-UNIT-4.pdf
ArshiniGubbala3
 
Functions in c++
Rokonuzzaman Rony
 
functIONS PROGRAMMING CIII II DJDJKASDJKJASD.pptx
nandemprasanna
 
C++ Functions.ppt
kanaka vardhini
 
power point presentation on object oriented programming functions concepts
bhargavi804095
 
Chp8_C++_Functions_Part2_User-defined functions.pptx
ssuser10ed71
 
Unit iv functions
indra Kishor
 
Ad

More from Ahmad177077 (12)

PPTX
Pointers in C++ object oriented programming
Ahmad177077
 
PPTX
Array In C++ programming object oriented programming
Ahmad177077
 
PPTX
Operators in c++ programming types of variables
Ahmad177077
 
PPTX
2. Variables and Data Types in C++ proramming.pptx
Ahmad177077
 
PPTX
Introduction to c++ programming language
Ahmad177077
 
PPTX
Selection Sort & Insertion Sorts Algorithms
Ahmad177077
 
PPTX
Strassen's Matrix Multiplication divide and conquere algorithm
Ahmad177077
 
PPTX
Recursive Algorithms with their types and implementation
Ahmad177077
 
PPTX
Graph Theory in Theoretical computer science
Ahmad177077
 
PPTX
Propositional Logics in Theoretical computer science
Ahmad177077
 
PPTX
Proof Techniques in Theoretical computer Science
Ahmad177077
 
PPTX
1. Introduction to C++ and brief history
Ahmad177077
 
Pointers in C++ object oriented programming
Ahmad177077
 
Array In C++ programming object oriented programming
Ahmad177077
 
Operators in c++ programming types of variables
Ahmad177077
 
2. Variables and Data Types in C++ proramming.pptx
Ahmad177077
 
Introduction to c++ programming language
Ahmad177077
 
Selection Sort & Insertion Sorts Algorithms
Ahmad177077
 
Strassen's Matrix Multiplication divide and conquere algorithm
Ahmad177077
 
Recursive Algorithms with their types and implementation
Ahmad177077
 
Graph Theory in Theoretical computer science
Ahmad177077
 
Propositional Logics in Theoretical computer science
Ahmad177077
 
Proof Techniques in Theoretical computer Science
Ahmad177077
 
1. Introduction to C++ and brief history
Ahmad177077
 
Ad

Recently uploaded (20)

PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PDF
Doc9.....................................
SofiaCollazos
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PPT
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
PDF
Architecture of the Future (09152021)
EdwardMeyman
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PPTX
Coupa-Overview _Assumptions presentation
annapureddyn
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
Doc9.....................................
SofiaCollazos
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
Architecture of the Future (09152021)
EdwardMeyman
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
Coupa-Overview _Assumptions presentation
annapureddyn
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 

6. Functions in C ++ programming object oriented programming

  • 1. 1 Functions in C++ Ahmad Baryal Saba Institute of Higher Education Computer Science Faculty Oct 21, 2024
  • 2. 2 Table of contents  What is function?  Why do we need functions?  Function structure  Function declaration  Types of functions  Function calling  Function call methods  Recursion  Inline Functions  Function overloading
  • 3. 3 Function C++  A function is a set of statements that takes input, does some specific computation, and produces output. The idea is to put some commonly or repeatedly done tasks together to make a function so that instead of writing the same code again and again for different inputs, we can call this function.  They also enable code reusability by allowing you to call a function multiple times within your program.
  • 4. 4 Why Do we Need Functions? • Functions help us in reducing code redundancy. If functionality is performed at multiple places in software, then rather than writing the same code, again and again, we create a function and call it everywhere. This also helps in maintenance as we have to make changes in only one place if we make changes to the functionality in future. • Functions make code modular. Consider a big file having many lines of code. It becomes really simple to read and use the code, if the code is divided into functions. • Functions provide abstraction. For example, we can use library functions without worrying about their internal work.
  • 5. 5 Function structure in c++ Let's break down the components of a C++ function: return_type: This is the data type of the value that the function will return after it has executed its task. If the function doesn't return a value, you can use void as the return type. function_name: This is the name you choose for your function, following the naming rules of C++. parameters: These are optional input values that the function can accept. Parameters are enclosed in parentheses and separated by commas. They allow you to pass information into the function for processing. Function body: This is the actual code that performs the specific task of the function. return (optional): If the return_type is not void, you can use the return statement to send a
  • 6. 6 Function Return Type in C++ The return type is the type of value returned by the function. A function in C++ may or may not return a value. If the function does not return a value then its return type is void. Value is returned from a function using the return statement. Control is transferred back to the caller when the return statement is executed. If the function returns a value then we need to specify its data type, like int, char, or float. Note: Only one value can be returned from a function in C++. It is mandatory to return a value for functions with a non-void return type. For example, consider a function calculateFactorial which calculates the factorial of a number and returns an integer value. We can see its return type is int. int calculateFactorial( int num) { int fact=1; for(int i=1;i<=num;i++) fact*=i; return fact; }
  • 7. 7 Types of Functions 1. User Defined Function are user/customer-defined blocks of code specially customized to reduce the complexity of big programs. They are also commonly known as “tailor-made functions” which are built only to satisfy the condition in which the user is facing issues meanwhile reducing the complexity of the whole program. 2. Library functions are also called “built-in Functions“. These functions are part of a compiler package that is already defined and consists of a special function with special and different meanings. Built-in Function gives us an edge as we can directly use them without defining them whereas in the user-defined function we have to declare and define a function before using them. For Example: sqrt(), sort(),pow(),reverse(),abs(), etc.
  • 8. 8 Calling a Function In C++, you can call a function by specifying the function's name, followed by parentheses containing any necessary arguments (if the function takes parameters). Here's the basic syntax for calling a function in C++: // Function declaration int add(int a, int b); int main() { int result = add(5, 3); // Calling the add function cout << "Result: " << result << endl; return 0; } // Function definition int add(int a, int b) { return a + b; }
  • 9. 9 There are two most popular ways to pass parameters: 1. Pass by Value: In this parameter passing method, values of actual parameters are copied to the function’s formal parameters. The actual and formal parameters are stored in different memory locations so any changes made in the functions are not reflected in the actual parameters of the caller. void incrementByValue(int x) { x++; // Increment the value of x cout << "Inside incrementByValue: x = " << x << endl; } int main() { int num = 5; cout << "Original value of num: " << num << endl; incrementByValue(num); cout << "After incrementByValue: num = " << num << endl; return 0; }
  • 10. 10 There are two most popular ways to pass parameters: 1. Pass by Reference: Both actual and formal parameters refer to the same locations, so any changes made inside the function are reflected in the actual parameters of the caller. void incrementByReference(int &x) { x++; // Increment the value referred to by x cout << "Inside incrementByReference: x = " << x << endl; } int main() { int num = 5; cout << "Original value of num: " << num << endl; incrementByReference(num); cout << "After incrementByReference: num = " << num << endl; return 0; }
  • 11. 11 Difference between call by value and call by reference in C++ Call by value  A copy of the value is passed to the function  Changes made inside the function are not reflected on other functions  Actual and formal arguments will be created at different memory location Call by reference  An address of value is passed to the function  Changes made inside the function are reflected outside the function as well  Actual and formal arguments will be created at same memory location.
  • 12. 12 Recursion in function Recursion is a programming concept where a function calls itself directly or indirectly to solve a problem. #include <iostream> using namespace std; // Recursive factorial function int factorial(int n) { // Base case: factorial of 0 is 1 if (n == 0 || n == 1) { return 1; } else { // Recursive case: n! = n * (n-1)! return n * factorial(n - 1); } } int main() { // Example usage of the factorial function int num = 5; cout << "Factorial of " << num << " is: " << factorial(num) << endl; return 0; }
  • 13. 13 Inline functions Inline functions in C++ are expanded by the compiler directly at the point of the function call, eliminating the overhead of a regular function call. Marked with the inline keyword. Pros: • Performance improvement by reducing function call overhead. • Compiler optimization opportunities. • Reduced time and space overhead on the call stack. Cons: • Potential code bloat due to duplicated code at call sites. • Compiler might choose not to inline based on its optimization criteria. • Can reduce code maintainability for complex functions.
  • 14. 14 Inline functions Example #include <iostream> using namespace std; // Definition of an inline function inline int square(int x) { return x * x; } int main() { int num = 5; // Inline function call int result = square(num); cout << "Square of " << num << " is: " << result << endl; return 0; }
  • 15. 15 Function overloading • Function overloading is a feature in C++ that allows multiple functions in the same scope with the same name but different parameter lists. • It provides a way to create functions that perform similar tasks but with variations in the type or number of parameters. Overloading Based on the Number and Type of Parameters: • Overloaded functions must differ in either the number or type of their parameters. • The compiler determines which function to call based on the number and types of arguments passed during the function call.
  • 16. 16 Example 1: Overloading Based on Number of Parameters: #include <iostream> using namespace std; // Function to add two integers int add(int a, int b) { return a + b; } // Overloaded function to add three integers int add(int a, int b, int c) { return a + b + c; } int main() { cout << "Sum of 2 and 3: " << add(2, 3) << endl; cout << "Sum of 2, 3, and 4: " << add(2, 3, 4) << endl; return 0; }
  • 17. 17 Example 2: Overloading Based on Type of Parameters: #include <iostream> using namespace std; // Function to add two integers int add(int a, int b) { return a + b; } // Overloaded function to concatenate two strings string add(const string& str1, const string& str2) { return str1 + str2; } int main() { cout << "Sum of 2 and 3: " << add(2, 3) << endl; cout << "Concatenation of 'Hello' and ' World': " << add("Hello", " World") << endl; return 0; }
  • 18. 18 Functions Using Pointers The function fun() expects a pointer ptr to an integer (or an address of an integer). It modifies the value at the address ptr. The dereference operator * is used to access the value at an address. In the statement ‘*ptr = 30’, the value at address ptr is changed to 30. The address operator & is used to get the address of a variable of any data type. In the function call statement ‘fun(&x)’, the address of x is passed so that x can be modified using its address. // C++ Program to demonstrate working of // function using pointers #include <iostream> using namespace std; void fun(int* ptr) { *ptr = 30; } int main() { int x = 20; fun(&x); cout << "x = " << x; return 0;