Functions in C++
A Function is a reusable block of code designed to perform
a specific task.
It helps break large programs into smaller, logical parts.
Functions make code cleaner, easier to understand, and
more maintainable.
Just like in other languages, C++ functions can take inputs
(called parameters), execute a block of statements, and
optionally return a result.
C++ also supports advanced features like function
overloading, default arguments, and inline functions,
which give more flexibility compared to C.
4.
Function Structure andUsage
Function Syntax in C++:
Return_type function_name(parameter_list)
{
//body of the function
}
Each part has a specific role:
Return type: Specifies what type of value the function returns. Use void if
there is no return value.
Function name: The name you will use to call the function.
Parameter list: Inputs that the function accepts. It can be empty if no
inputs are needed.
Function body: The block of code that runs when the function is called.
5.
Function Declaration vsDefinition
Function Declaration introduces the function to the compiler.
It tells the compiler the return type, name, and parameters but does not
include the body.
It ends with a semicolon.
// Declaration
int add(int, int);
Function Definition provides the actual implementation of the function.
int add(int a, int b) {
return a + b;
}
6.
Calling a Function
Once a function is defined, you can use it by simply calling its name followed by
parentheses.
This tells the program to execute the code inside that function.
If the function takes parameters, you pass the required values inside the parentheses.
If it doesn’t take any parameters, you just use empty parentheses.
void greet() {
cout << "Welcome to C++ Programming!" << endl; }
int multiply(int a, int b) {
return a * b; }
int main() {
greet();
int result = multiply(4, 5);
cout << "Multiplication result: " << result << endl;
return 0;
}
7.
Types of Functionsin C++
In C++, functions can be broadly categorized based on two
criteria:
1. Based on origin:
Library Functions: These are built-in functions provided
by C++ standard libraries, such as cout, sqrt(), abs(), and
getline(). You can use them by including appropriate
headers like <iostream>, <cmath>, or <string>.
User-Defined Functions: These are functions created by
the programmer to perform specific tasks in the program.
8.
2. Based oninput and return type:
User-defined functions can be further classified based on whether
they accept parameters or return a value:
1. No parameters, no return value: The function performs a task
but does not take input or return anything.
2. Parameters, no return value: The function takes input but does
not return a result.
3. No parameters, return value: The function returns a result but
does not take any input.
4. Parameters and return value: The function takes input and
returns a result.
C++ Arrays
Anarray is a collection of elements of the same type
placed in contiguous memory locations.
It allows you to store multiple values under a single name
and access them using an index.
Arrays are one of the most basic and commonly used data
structures in C++ programming
11.
Create an Array
We can create/declare an array by simply specifying the
data type first and then the name of the array with its
size inside [] square brackets(better known as array
subscript operator).
Syntax:
data_type array_name [size];
Example:
int arr[5];
This will create an array with name arr that
can store 5 integers.
12.
Initialize the Array
Initialization means assigning initial values to array elements. We can
initialize the array with values enclosed in curly braces '{}' are assigned to
the array.
For example: int arr[5] = {2, 4, 8, 12, 16};
int arr[5] = {2, 4, 8};
int arr[] = {2, 4, 8, 12, 16};
int arr[5] = {0};
13.
Access Array Elements
Elements of an array can be accessed by their position (called index) in the
sequence.
In C++, indexes of an array starts from 0 instead of 1.
We just have to pass this index inside the [] square brackets with the array
name as shown:
array_name[index];
It is important to note that index cannot be negative or greater than size of the
array minus 1. (0 ≤ index ≤ size - 1).
14.
Update Array Elements
To change the element at a particular index in an array, just use the “=”
assignment operator with new value as right hand expression while accessing
the array element.
array_name[index] = value;
Example:
int arr[] = {2, 4, 8, 12, 16};
arr[0] = 90;
15.
Traverse Array
Traversingmeans visiting each element one by one.
The advantage of array is that it can be easily traversed by using a
loop with loop variable that runs from 0 to size - 1.
We use this loop variable as index of the array and access each
element one by one sequentially.
int arr[5] = {2, 4, 8, 12, 16};
// Traversing and printing arr
for (int i = 0; i < 5; i++)
cout << arr[i] << " ";
16.
Size of Array
The size of the array refers to the number of elements that can be stored in
the array.
The array does not contain the information about its size but we can extract
the size using sizeof() operator.
17.
string letters[2][2][2] ={
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};
Multi-Dimensional Arrays
A multi-dimensional array is an array of arrays.
To declare a multi-dimensional array, define the variable
type, specify the name of the array followed by square
brackets which specify how many elements the main array
has, followed by another set of square brackets which
indicates how many elements the sub-arrays have.
string letters[2][4];
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
18.
Types of MultidimensionalArrays
We can have any number of dimensions in an array as per requirement, but
the complexity of handling them also increases exponentially.
That is why, the most widely used multidimensional arrays are:
1. Two-Dimensional Array (2D Array)
2. Three-Dimensional Array (3D Array)
2D Array:
A two-dimensional array in C++ is a collection of elements organized the
form of rows and columns. It can be visualized as a table or a grid.
3D Array:
A three-dimensional array in C++ is a collection of elements organized in a 3D
cuboid-like structure. It can be visualized as a series of two-dimensional
arrays stacked on top of each other.
What is aReference?
A reference is an alias for an already existing variable.
Declared using the ampersand (&) operator (e.g., int& ref;)
Must be initialized when declared
Cannot be nullptr
Cannot be reassigned to another variable
Dereferenced implicitly
Arithmetic operations not supported
29.
Reference - MoreExplanation
References provide safer, simpler access to variables.
Commonly used in function parameters and return types
Ideal for avoiding copying of large data
Often used in operator overloading
int b = 20;
int& ref = b;
Conclusion
Pointers: Usewhen dynamic memory allocation or pointer arithmetic
is needed.
References: Use when you need a simple alias for passing parameters
or returning values without copying.
Prefer references over pointers when null values and reassignment
are not needed.
Function Objects (Functors)
These are objects of a class that overload the
function call operator (operator()), allowing them
to be called like functions.
Definition: A class is created with a public
operator() member function.
Usage: Instances of this class can then be "called"
with arguments, just like regular functions.
Benefits: Functors can maintain state (data
members) between calls, unlike plain
functions. They are widely used in the C++
Standard Library, particularly with algorithms and
containers for custom operations (e.g., custom
sorting criteria).
Classes & Structures
In C++, both classes and structures are user-defined data
types that allow grouping data members and member
functions into a single unit.
They serve as blueprints for creating objects, which are
instances of these types.
38.
Classes
Defined usingthe class Keyword.
By default, members (data and functions) within a
class are private.
This means they can only be accessed from within
the class itself or by its friend functions/classes.
Classes are fundamental to Object-Oriented
Programming (OOP) in C++ and are commonly used
to encapsulate data and behavior, providing
controlled access through public interfaces.
Support advanced OOP concepts like inheritance
and polymorphism.
40.
Structures:
Defined usingthe struct keyword.
By default, members within a structure are
public. This means they can be accessed directly
from outside the structure.
Historically, structures in C were primarily used to
group related data. In C++, structures have been
extended to also include member functions,
constructors, destructors, and support
inheritance, making them almost identical to
classes in functionality.
Often used for simple data structures where
public access to members is acceptable or when
interfacing with C code that uses structures.
FRIEND FUNCTIONS
Afriend function is a function which is declared
within a class and is defined outside the class.
It does not require any scope resolution operator
for defining.
It can access private members of a class. It is
declared by using keyword “friend”.
The scope resolution operator :: allows us to
define a member function of a class outside
the class definition.
44.
How to declareFriend Function :
Friend function declaration should be inside the
class using the Friend key word.
Syntax:
friend ret_type
func_name(arguments);
Definition of friend function is specified outside
the class.
Function definition must not use keyword friend.
45.
Friend function characterstics:
It is not in scope of class.
It cannot be called using object of that class.
It can be invoked like a normal function.
It has objects as arguments.
Friend Functions are majorly used in operator
overlading.
Friendship is not inherited by derived classes.
Inline Functions:
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.
Any change to an inline function could require all
clients of the function to be recompiled because
compiler would need to replace all the code once
again otherwise it will continue with old
functionality.
49.
Defining an InlineFunction
To define an inline 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.
inline int Max(int x, int y)
{
return (x > y)? x : y;
}
Passing an Objectas argument
To pass an object as an argument we write the
object name as the argument while calling the
function the same way we do it for other
variables.
Syntax:
function_name(object_name);
54.
Returning objects fromfunctions
In C++, a function can return an object of a class.
This helps send complete data (like multiple
values) from the function back to the main
program.
The returned object can be used to call its
methods or access its data.
This is useful in object-oriented programming for
better data handling.
In C++,data can be sent to functions when they are called in
order to perform operations. This data is called parameters or
arguments and there are various parameter passing methods
available in C++.
Before you see the techniques, first understand the difference
between the following terms:
Formal Parameters: Variables used in parameter list of a function
as placeholders. Also called only parameters.
Actual Parameters: The expressions or values passed in during a
function call. Also called arguments.
There are 3 different methods using which we can pass
parameters to a function in C++. These are:
Table of Content
Pass by Value
Pass by Reference
Pass by Pointer
58.
Pass by Value
In pass by value method, a variable's value is
copied and then passed to the function.
As the result, any changes to the parameter inside
the function will not affect the variable's original
value in the caller.
This method is simple, easy to understand and
implement but it is not preferred for large size of
data structures at it involves copying the value.
59.
Pass By Value
#include<iostream>
using namespace std;
int change(int a) {
a = 22;
return a;
}
int main() {
int x = 5;
cout << x<<endl;
cout << change(x)<<endl;
cout << x;
return 0;
}
60.
Pass By Reference
In pass-by-reference method, instead of passing
the value of the argument, we pass the reference
of an argument to the function.
This allows the function to change the value of
the original argument.
This is useful when you have to pass large size
data.
It is Suitable when you want to modify the original
data or avoid copying large data.
61.
Pass By Reference
#include<iostream>
using namespace std;
int change(int &a) {
a = 22;
return a;
}
int main() {
int x = 5;
cout << x<<endl;
cout << change(x)<<endl;
cout << x;
return 0;
}
Function Overloading
• Overloadingis nothing but two or more functions is defined with same name but
different parameters Function overloading can be considered as an example of
polymorphism feature in C++.
• Function overloading is a compile-time polymorphism.
• Rules for Function overloading :
• An overloaded function must have :
Different type of parameters
ex:void test(int a); void test(float a);
Different number of parameters
ex: void test(); void test(int a);
Different sequence of parameters
ex: void test(int a , float b); void tes t(float a , int b);
Virtual Function:
• Avirtual function (also known as virtual methods) is a member function
that is declared within a base class and is re-defined (overridden) by a
derived class.
• When you refer to a derived class object using a pointer or a reference
to the base class, you can call a virtual function for that object and
execute the derived class's version of the method.
• Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for the function call.
• They are mainly used to achieve Runtime polymorphism.
• Functions are declared with a virtual keyword in a base class.
• The resolving of a function call is done at runtime.
Array of Objects
•An array of objects in C++ is a collection of objects of the same class
type stored in contiguous memory locations.
• It allows you to create & manage multiple objects with similar
properties & behaviors in a single data structure.
• Each element in the array represents an individual object, and you
can access these objects using their respective indices.
• By using an array of objects, you can efficiently perform operations
on multiple objects simultaneously, like initialization, data
manipulation, and iteration.
• This helps in code organization, reduces redundancy, and simplifies
common tasks when working with a group of related objects.
72.
Declaration Of ArrayOf Objects In C++
• To declare an array of objects in C++, you need to specify the class
name followed by the array name and the desired size of the
array.
• The syntax for declaring an array of objects is:
ClassName arrayName[size];
73.
Initializing Array OfObjects In C++
• After declaring an array of objects, you need to initialize the
objects with appropriate values. There are several ways to initialize
an array of objects in C++, like:
• 1. Using the default constructor: If the class has a default
constructor (a constructor that takes no arguments), you can
simply declare the array, and each object will be initialized with the
default constructor
• ClassName arrayName[size];
74.
• 2. Usingan initialization list: You can use an initialization list to
provide initial values for each object in the array at the time of
declaration.
ClassName arrayName[size] = { { arguments_for_object1 },
{ arguments_for_object2 }, ... };
Example:
Rectangle rectangles[3] = { {3, 4}, {5, 6}, {7, 8} }
75.
• 3. Usinga loop to initialize objects: You can use a loop to iterate over
the array and initialize each object individually.
for (int i = 0; i < size; i++) {
// Initialize each object using member functions or assignment
arrayName[i].memberFunction(arguments);
arrayName[i].dataMember = value;
}
For example:
for (int i = 0; i < 5; i++) {
rectangles[i].setDimensions(i+1, i+2);
}
77.
Advantages of Arrayof Objects
1. Efficient memory allocation: An array of objects allows you to allocate memory for
multiple objects in a single block, which is more efficient than allocating memory for each
object individually. This contiguous memory allocation improves cache locality & reduces
memory fragmentation.
2. Simplified data management: By storing objects in an array, you can manage and
manipulate related data more easily. You can access objects using their index, perform
operations on multiple objects simultaneously, and iterate over the array using loops, making
your code more concise and readable.
3. Code reusability & organization: Arrays of objects promote code reusability by allowing
you to create and work with multiple instances of a class using a single data structure. This
helps organize your code, reduce duplicated code, and make it easier to maintain and modify.
4. Sorting and searching operations: Arrays of objects can be efficiently sorted and searched
using various algorithms. You can apply sorting techniques like bubble sort, insertion sort, or
quick sort directly to the array and perform binary search on sorted arrays to quickly find
specific objects
78.
Disadvantages of Arrayof Objects
1. Fixed size: Arrays of objects have a fixed size that is determined at the time of declaration
or allocation. Once the size is set, it cannot be changed dynamically. If you need to add or
remove objects from the array, you have to create a new array with the desired size and copy
the existing objects, which can be inefficient and time-consuming.
2. Lack of flexibility: Arrays of objects provide a rigid structure for storing objects. If you
need to insert or delete objects in the middle of the array, you have to shift all the
subsequent objects to maintain the contiguous memory layout. This can be costly in terms of
time complexity, especially for large arrays.
3. Memory wastage: If you allocate an array of objects with a specific size and don't use all
the elements, the unused memory is wasted. This can lead to inefficient memory utilization,
especially if the array size is large and the number of actually used objects is small.
4. Difficulty in resizing: Resizing an array of objects is not an easy operation. You need to
create a new array with the desired size, copy the existing objects to the new array, and then
delete the old array. This process can be time-consuming and requires manual memory
management, which can be error-prone.
Pointers:
• Pointers inC++ are the variables that store the address of another variable. Similarly, a
pointer to an object is the variable that holds the address of an object. Data members
and member functions of an object can be accessed using pointers. There are majorly
four types of pointers.
• Null pointer: When we assign a NULL value to the pointer, it is called a Null pointer.
• Void pointer: A void pointer have no data type associated with it. It can store address of
any data type. A void pointer is declared with a void keyword. To print its value it must
be typecasted.
• Wild pointer: This type of pointer is only declared and not assigned the address of any
variable.
• Dangling pointer: When a pointer points toward the variable whose memory we have
de-allocated, it is known as a Dangling pointer.
81.
Syntax of aPointer
• The syntax of a pointer in C++ is given below.
int a=3;
int *ptr=&a;
• Here data type of the pointer is the same as the variable's data type, where
‘*’ is the indirection operator, and ‘&’ is the address operator.
82.
Pointer to Object
•Apointer to an object is a variable that stores the address of an object in memory.
•Just like we use pointers for primitive types (int*, float*), we can also create pointers for class
objects.
Declaration:
ClassName *ptr;
Accessing Members:
• For normal objects: object.member
• For pointers: ptr -> member (array operator
This Pointer
• The'this' pointer contains the address of the current object.
• in other words, this pointer points to the class's current object.
• Each object receives its copy of data members, whereas all objects
share a single copy of member functions.
• All non-static member function calls receive the 'this' pointer as a
secret parameter, and all the non-static functions have it as a local
variable.
• The static member functions can be called without any object due
to which the 'this' reference is not available (with class name).
86.
Example:
• When thename of a local variable and the name of a member
is the same.
• When the name of a local variable and the name of a member
is the same, you won't be able to assign the local variable value
to the data members until you use this pointer because the
compiler won't recognize that you're referring to the object's
data members unless you use this reference.
dynamic memory allocations
•In C++, stack memory is automatically allocated for variables at
compile time and has a fixed size.
• For greater control and flexibility, dynamic memory allocation on
the heap is used, allowing manual allocation with new and
deallocation with delete.
• It allows the program to request memory from the heap at runtime
using the new operator and release it using the delete operator.
• This is useful when the size of required memory isn’t known at
compile time, such as for variable-sized arrays or dynamic data
structures like linked lists and trees.
Allocate Block ofMemory (Array)
• A new operator is also used to dynamically allocate a block (an array)
of memory of given data type as shown below:
• new data_type[n];
• This statement dynamically allocates memory for n elements of
given data_type. Arrays can also be initialized during allocation.
What if enoughmemory is not
available during runtime?
• If enough memory is not available in the heap to allocate, the new
request indicates failure by throwing an exception of type std::
bad_alloc, unless "nothrow" is used with the new operator, in
which case it returns a nullptr pointer. Therefore, it may be a good
idea to check for the pointer variable produced by the new before
using its program.