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,
we can call the function.
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 change at one place if we make future changes
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
divided into functions.
● Functions provide abstraction. For example, we can use library functions
without worrying about their internal working.
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
function declaration is optional in the function declaration, but it is necessary to put
them in the definition. Below are an example of function declarations. (parameter
names are not there in below declarations)
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 change at one place if we make future changes 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 divided into
functions.
● Functions provide abstraction: For example, we can use library functions without
worrying about their internal working.
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
function declaration is optional in the function declaration, but it is necessary to put
them in the definition. Below are an example of function declarations. (parameter
names are not there in below declarations)
// 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
Parameter Passing to functions
● The parameters passed to function are called actual parameters. For example, in
the above program 10 and 20 are actual parameters.
● The parameters received by function are called f ormal parameters. For example,
in the above program x and y are formal parameters.
There are two most popular ways to pass parameters.
● Pass by Value: In this parameter passing method, values of actual parameters
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
not reflected in actual parameters of caller.
● 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 in C++
Inline function is one of the important feature of C++. So, let’s first understand why
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
overhead if the execution time of function is less than the switching time from the caller
function to called function (callee). For functions that are large and/or perform complex
tasks, the overhead of the function call is usually insignificant compared to the amount
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
actually execute the function’s code. This overhead occurs for small functions because
execution time of small function is less than the switching time.
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
function call. This substitution is performed by the C++ compiler at compile time. Inline
function may increase efficiency if it is small.
The syntax for defining the function inline is:
inline return-type function-name(parameters)
{
// function code
}
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:
1) If a function contains a loop. (for, while, do-while)
2) If a function contains static variables.
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.
5) If a function contains switch or goto statement.
Inline functions provide following advantages:
1) Function call overhead doesn’t occur.
2) It also saves the overhead of push/pop variables on the stack when function is
called.
3) It also saves overhead of a return call from a function.
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
context and the called context.
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.
Inline function disadvantages:
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
increase drastically then it would surely cause an overhead on register utilization.
2) If you use too many inline functions then the size of the binary executable file will be
large, because of the duplication of same code.
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,
otherwise it will continue with old functionality.
5) Inline functions may not be useful for many embedded systems. Because in
embedded systems code size is more important than speed.
6) Inline functions might cause thrashing because inlining might increase size of the
binary executable file. Thrashing in memory causes performance of computer to
degrade.
The following program demonstrates the use of use of inline function.
#include <iostream>
using namespace std;
inline int cube(int s)
{
return s*s*s;
}
int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
}
Output: The cube of 3 is: 27
Inline function and classes:
It is also possible to define the inline function inside the class. In fact, all the functions
defined inside the class are implicitly inline. Thus, all the restrictions of inline functions
are also applied here. If you need to explicitly declare inline function in the class then
just declare the function inside the class and define it outside the class using inline
keyword.
For example:
class S
{
public:
inline int square(int s) // redundant use of inline
{
// this function is automatically inline
// function body
}
};
The above style is considered as a bad programming style. The best programming style
is to just write the prototype of function inside the class and specify it as an inline in the
function definition.
For example:
class S
{
public:
int square(int s); // declare the function
};
inline int S::square(int s) // use inline prefix
{
}
The following program demonstrates this concept:
#include <iostream>
using namespace std;
class operation
{
int a,b,add,sub,mul;
float div;
public:
void get();
void sum();
void difference();
void product();
void division();
};
inline void operation :: get()
{
cout << "Enter first value:";
cin >> a;
cout << "Enter second value:";
cin >> b;
}
inline void operation :: sum()
{
add = a+b;
cout << "Addition of two numbers: " << a+b << "\n";
}
inline void operation :: difference()
{
sub = a-b;
cout << "Difference of two numbers: " << a-b << "\n";
}
inline void operation :: product()
{
mul = a*b;
cout << "Product of two numbers: " << a*b << "\n";
}
inline void operation ::division()
{
div=a/b;
cout<<"Division of two numbers: "<<a/b<<"\n" ;
}
int main()
{
cout << "Program using inline function\n";
operation s;
s.get();
s.sum();
s.difference();
s.product();
s.division();
return 0;
}
Output:
Enter first value: 45
Enter second value: 15
Addition of two numbers: 60
Difference of two numbers: 30
Product of two numbers: 675
Division of two numbers: 3
Friend class and function in C++
Friend Class A friend class can access private and protected members of other class in
which it is declared as friend. It is sometimes useful to allow a particular class to
access private members of other class. For example a LinkedList class may be allowed
to access private members of Node.
class Node {
private:
int key;
Node* next;
/* Other members of Node Class */
// Now class LinkedList can
// access private members of Node
friend class LinkedList;
};
Friend Function Like friend class, a friend function can be given special grant to access
private and protected members. A friend function can be:
a) A method of another class
b) A global function
Following are some important points about friend functions and classes:
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
value of encapsulation of separate classes in object-oriented programming.
2) Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of
A automatically.
3) Friendship is not inherited (See t his for more details)
4) The concept of friends is not there in Java.
A simple and complete C++ program to demonstrate friend Class
#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
using friend function of C++.
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
function or friend class can also access private data members.
Is it possible to access private members outside a class without friend?
Yes, it is possible using pointers. See the following program as an example.
#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.