Functions in C++
Functions in C++
A function is a set of statements that take inputs, do some specific computation and
produces output.
The idea is to put some commonly or repeatedly done task together and make a
function so that instead of writing the same code again and again for different inputs,
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
to the functionality.
● Functions make code modular. Consider a big file having many lines of
codes. It becomes really simple to read and use the code if the code is
Function Declaration
A function declaration tells the compiler about the number of parameters function
takes, data-types of parameters and return type of function. Putting parameter names in
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
functionality.
● Functions make code modular: Consider a big file having many lines of codes. 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
Function Declaration
A function declaration tells the compiler about the number of parameters function
takes, data-types of parameters and return type of function. Putting parameter names in
// An example function that takes two parameters 'x' and 'y'
// as input and returns max of two input numbers
int max(int x, int y)
{
if (x > y)
return x;
else
return y;
}
// main function that doesn't receive any parameter and
// returns integer.
int main(void)
{
int a = 10, b = 20;
int m = max(a, b); // Calling above function to find max of 'a' and 'b'
printf("m is %d", m);
return 0;
}
Output:
m is 20
● The parameters passed to function are called actual parameters. For example, in
are copied to function’s formal parameters and the two types of parameters are
stored in different memory locations. So any changes made inside functions are
● Pass by Reference Both actual and formal parameters refer to same locations, so
any changes made inside the function are actually reflected in actual parameters
of caller.
inline functions are used and what is the purpose of inline function?
When the program executes the function call instruction the CPU stores the memory
address of the instruction following the function call, copies the arguments of the
function on the stack and finally transfers control to the specified function. The CPU
then executes the function code, stores the function return value in a predefined
memory location/register and returns control to the calling function. This can become
of time the function takes to run. However, for small, commonly-used functions, the
time needed to make the function call is often a lot more than the time needed to
C++ provides an inline functions to reduce the function call overhead. Inline function is
a function that is expanded in line when it is called. When the inline function is called
whole code of the inline function gets inserted or substituted at the point of inline
Remember, inlining is only a request to the compiler, not a command. Compiler can
ignore the request for inlining. Compiler may not perform inlining in such circumstances
like:
3) If a function is recursive.
4) If a function return type is other than void, and the return statement doesn’t exist in
function body.
2) It also saves the overhead of push/pop variables on the stack when function is
called.
4) When you inline a function, you may enable compiler to perform context specific
optimization on the body of function. Such optimizations are not possible for normal
function calls. Other optimizations can be obtained by considering the flows of calling
5) Inline function may be useful (if it is small) for embedded systems because inline can
yield less code than the function call preamble and return.
1) The added variables from the inlined function consumes additional registers, After
in-lining function if variables number which are going to use register increases than they
may create overhead on register variable resource utilization. This means that when
inline function body is substituted at the point of function call, total number of variables
used by the function also gets inserted. So the number of register going to be used for
the variables will also get increased. So if after function inlining variable numbers
2) If you use too many inline functions then the size of the binary executable file will be
3) Too much inlining can also reduce your instruction cache hit rate, thus reducing the
speed of instruction fetch from that of cache memory to that of primary memory.
4) Inline function may increase compile time overhead if someone changes the code
inside the inline function then all the calling location has to be recompiled because
compiler would require to replace all the code once again to reflect the changes,
5) Inline functions may not be useful for many embedded systems. Because in
6) Inline functions might cause thrashing because inlining might increase size of the
degrade.
access private members of other class. For example a LinkedList class may be allowed
1) Friends should be used only for limited purpose. too many functions or external
classes are declared as friends of a class with protected or private data, it lessens the
2) Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of
A automatically.
#include <iostream>
class A {
private:
int a;
public:
A() { a = 0; }
friend class B; // Friend Class
};
class B {
private:
int b;
public:
void showA(A& x)
{
// Since B is friend of A, it can access
// private members of A
std::cout << "A::a=" << x.a;
}
};
int main()
{
A a;
B b;
b.showA(a);
return 0;
}
Output:
A::a=0
A simple and complete C++ program to demonstrate friend function of another class
#include <iostream>
class B;
class A {
public:
void showB(B&);
};
class B {
private:
int b;
public:
B() { b = 0; }
friend void A::showB(B& x); // Friend function
};
void A::showB(B& x)
{
// Since showB() is friend of B, it can
// access private members of B
std::cout << "B::b = " << x.b;
}
int main()
{
A a;
B x;
a.showB(x);
return 0;
}
Output:
B::b = 0
A simple and complete C++ program to demonstrate global friend
#include <iostream>
class A {
int a;
public:
A() { a = 0; }
// global friend function
friend void showA(A&);
};
void showA(A& x)
{
// Since showA() is a friend, it can access
// private members of A
std::cout << "A::a=" << x.a;
}
int main()
{
A a;
showA(a);
return 0;
}
Output:
A::a = 0
Program to swap two members using Friend Function
CASE 1:
Given two numbers a & b, swap these two numbers using friend function of C++.
Examples:
Input : a = 5, b = 9
Output : a = 9, b = 5
Input : a = 4, b = 6
Output : a= 6, b = 4
Approach:
Create a class Swap, declare three variable in it, i.e., a, b, and temp and create a
constructor for inputs. Declare a friend function in it. Define the friend function outside
the class scope by taking arguments as call by reference to pass the copy of Swap
Object. Perform the swap operation with Swap variables.
// C++ Program to swap two numbers using friend function
#include <iostream>
using namespace std;
class Swap {
// Declare the variables of Swap Class
int temp, a, b;
public:
// Define the parametrized constructor, for inputs
Swap(int a, int b)
{
this->a = a;
this->b = b;
}
// Declare the friend function to swap, take arguments
// as call by reference
friend void swap(Swap&);
};
// Define the swap function outside class scope
void swap(Swap& s1)
{
// Call by reference is used to passed object copy to
// the function
cout << "\nBefore Swapping: " << s1.a << " " << s1.b;
// Swap operations with Swap Class variables
s1.temp = s1.a;
s1.a = s1.b;
s1.b = s1.temp;
cout << "\nAfter Swapping: " << s1.a << " " << s1.b;
}
// Driver Code
int main()
{
// Declare and Initialize the Swap object
Swap s(4, 6);
swap(s);
return 0;
}
Output:
Before Swapping: 4 6
After Swapping: 6 4
CASE 2:
Given two objects s1 & s2 of a class, swap the data members of these two objects
Examples:
Input : a = 6, b = 10
Output : a = 10, b = 6
Input : a = 4, b = 6
Output : a= 6, b = 4
Approach:
Create a class Swap, declare one variable in it, i.e., num and create a constructor for
inputs. Declare a friend function in it. Define the friend function outside the class scope
by taking arguments as call by reference to pass the copy of Swap Object. Perform the
swap operation.
//C++ Program to swap data members of two objects of a class using friend function.
#include <iostream>
using namespace std;
class Swap {
// Declare the variable of Swap Class
int num;
public:
// Define the parametrized constructor, for input.
Swap(int num)
{
this->num = num;
}
// Declare the friend function to swap, take arguments
// as call by reference
friend void swap(Swap&, Swap&);
};
// Define the swap function outside class scope
void swap(Swap& s1, Swap& s2)
{
// declare a temporary variable.
int temp;
// Call by reference is used to passed object copy to
// the function
cout << "\nBefore Swapping: " << s1.num << " " << s2.num;
// Swap operations with objects of class Swap
temp = s1.num;
s1.num = s2.num;
s2.num = temp;
cout << "\nAfter Swapping: " << s1.num << " " << s2.num;
}
int main()
{
// Declare and Initialize the objects of Swap class
Swap s1(6), s2(10);
swap(s1,s2);
return 0;
}
Output:
Before Swapping: 6 10
After Swapping: 10 6
Can we access private data members of a class without
using a member or a friend function?
The idea of Encapsulation is to bundle data and methods (that work on the data)
together and restrict access of private data members outside the class. In C++, a friend
#include<iostream>
using namespace std;
class Test
{
private:
int data;
public:
Test() { data = 0; }
int getData() { return data; }
};
int main()
{
Test t;
int* ptr = (int*)&t;
*ptr = 10;
cout << t.getData();
return 0;
}
Note that the above way of accessing private data members is not at all a
recommended way of accessing members and should never be used. Also, it doesn’t
mean that the encapsulation doesn’t work in C++. The idea of making private members
is to avoid accidental changes. The above change to data is not accidental. It’s an
intentionally written code to fool the compiler.