0% found this document useful (0 votes)
23 views40 pages

C++ Inline and Friend Functions Explained

The document covers key concepts of Object-Oriented Programming (OOP) in C++, including inline functions, friend functions, function overloading, and inheritance. Inline functions improve execution speed by reducing function call overhead, while friend functions allow non-member functions to access private data. Inheritance promotes code reusability and reduces redundancy by enabling derived classes to inherit properties from base classes.

Uploaded by

1stformybegining
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views40 pages

C++ Inline and Friend Functions Explained

The document covers key concepts of Object-Oriented Programming (OOP) in C++, including inline functions, friend functions, function overloading, and inheritance. Inline functions improve execution speed by reducing function call overhead, while friend functions allow non-member functions to access private data. Inheritance promotes code reusability and reduces redundancy by enabling derived classes to inherit properties from base classes.

Uploaded by

1stformybegining
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit 7

Object-Oriented Programming
Concepts
7.1 Inline function
• We say that using functions in a program is to save some memory space because all the
calls to the functions cause the same code to be executed. However, every time a function
is called, it takes a lot of extra time in executing a series of instructions.
• Since the tasks such as jumping to the function, saving registers, pushing arguments into
the stack and returning to the calling function are carried out when a function is called.
When a function is small, considerable amount of time is spent in such overheads.
• C++ has a solution for this problem. To eliminate the cost of calls to small functions, C++
proposed a new feature called INLINE function.
• When a function is defined as inline, compiler copies its body where the function call is
made, instead of transferring control to that function. So, it is used only for small functions.
• A function is made inline by using a keyword “inline” before the function definition.
• It should be noted that, the inline keyword is just a request to the compiler to make the
function inline function, not a command.
• The compiler may not always accept this request. It may ignore the request if the function
is too long or complicated and compile the function as normal function. Some situations
where inline expansion may not work are:
✓ for functions having loop, switch or go-to statements
✓ for recursive functions
✓ functions with static variables
✓ for functions not returning values, if a return statement exists
• Advantage: Increase execution speed.
• Disadvantages: More memory required because of copying.
Example 1:
#include<conio.h>
#include<iostream>
using namespace std;
//While declartion no need for keyword inline
int Findcube(int x);
int main()
{
cout<<Findcube(3);
getch();
return 0;
}
inline int Findcube(int x)
{
return x*x*x;
}

Example 2:
#include<iostream.h>
inline float lbtokg(float lbs)
{
return (0.453 * lbs);
}
int main()
{
float lbs, kgs;
cout<<”Enter weight in lbs:”;
cin>>lbs;
kgs=lbtokg(lbs);
cout<<”Weight in kg is ”<<kgs;
return (0);
}
Example 3:
WAP to display hello world by using class and inline member function.

#include<iostream>
using namespace std;
class Demo
{
public:
inline void display();
};
int main()
{
Demo d;
[Link]();
}
inline void Demo:: display() //Defining outside the class
{
cout<<"hello world";
}

7.2 Friend Function


• One of the important concepts of is data hiding, i.e., a nonmember function cannot access
an object's private or protected data.
• But sometimes this restriction may force programmer to write long and complex codes. So,
there is mechanism built in C++ programming to access private or protected data from non-
member functions.
• This is done using a friend function or/and a friend class.
• A function is said to be a friend function of a class if it can access the members (including
private members and protected) of the class even if it is not the member function of this
class.
• In other words, a friend function is a non-member function that has access to the private
members of the class. The complier knows a given function is a friend function by the use of the
keyword friend.
• Characteristics of a friend function: -
✓ A friend function can be either global or a member of some other class.
✓ Since, friend function is not a part of the class, it can be declared anywhere in the
public, private and protected section of the class.
✓ It cannot be called by using the object of the class since it is not in the scope of the
class.
✓ It is called like a normal function without the help of any object.
✓ Unlike member functions, it cannot access member names directly. So, it has to use
an object name and dot operator with each member name (like A.x)
✓ It, generally, takes objects as arguments
• Friends are not in the class’s scope, and they aren’t called using the member selection
operators (. Or >).
• For accessing the data, the declaration of a friend function should be made inside the body
of the class (can be anywhere inside class either in private or public section) starting with
keyword friend.
• Syntax:
class class_name
{
… .. …
friend return_type function_name(arguments);
… .. …
}
return_type functionName(argument/s)
{
… .. …
// Private and protected data of class_Name can be accessed from
// this function because it is a friend function of className.
… .. …
}
• Example 1:
WAP to find the sum of two numbers using the concept of friend function.
#include<iostream>
using namespace std;
class Demo
{
int fn,sn;
public:
void setdata()
{
cout<<"Enter two number"<<endl;
cin>>fn>>sn;
}
friend void sum(Demo d);
};
void sum(Demo d)
{
int sum;
sum=[Link]+[Link];
cout<<"Sum= "<<sum;
}
int main()
{
Demo a;
[Link]();
sum(a);
}
• Example 2:
#include <iostream>
Using namespace std;
class Avg
{
int n1,n2;
public:
void getn()
{
cin>>n1>>n2;
}
friend int average(Avg a);
};
//here “friend” is a keyword to specify that the function declared is a friend function
//int is a return type of the friend function
//average is the name of the friend function
//Avg is the type of the argument type
//a is an argument

int average(Avg a) //friend function definition


{
return((a.n1 + a.n2)/2);
}
int main()
{
Avg obj1;
[Link]();
cout<<”Mean:”<<average(obj1); //friend function called
return 0;
}
How can we make two classes friendly?
i. Common friend function on both classes
#include<iostream>
Using namespace std;
class beta; // needed for frenfunction declaration
class alpha
{
private:
int data;
public:
void get_data()
{
cin>>data;
}
friend int frenfunction(alpha, beta); // friend function
};
class beta
{
private:
int data;
public:
void get_data()
{
cin>>data;
}
friend int frenfunction(alpha, beta); // friend function
};
int frenfunction(alpha a,beta b)
{
return([Link]+[Link]);
}
int main()
{
alpha aa;
beta bb;
aa.get_data();
bb.get_data();
cout<<frenfunction(aa,bb)<<endl;
return 0;
}
ii. Friend Class Technique
Like friend function, a class can also be a friend of another class. A friend class can access
all the private and protected members of other class. In order to access the private and
protected members of a class into friend class we must pass on object of a class to the
member functions of friend class.
Example:
#include<iostream>
using namespace std;
class Rectangle
{
int L,B;
public:
Rectangle()
{
L=10;
B=20;
}
friend class Square; //Statement 1
};
//Friend class
class Square
{
int S;
public:
Square()
{
S=5;
}
void Display(Rectangle Rect)
{
cout<<"\n\tLength : "<<Rect.L;
cout<<"\n\tBreadth : "<<Rect.B;
cout<<"\n\tSide : "<<S;
}
};
int main()
{
Rectangle R;
Square S;
[Link](R); //Statement 2
}
[Link] classes called class1 and class2 with each of having one private member. Add member
function to set a value (say setvalue) on each class. Add one more function max () that is friendly
to both classes. max() function should compare two private member of two classes and show
maximum among them. Create one-one object of each class then set a value on them. Display the
maximum number among them.
#include<iostream>
using namespace std;
class Class2;// forward declaration
class Class1
{
int a;
public:
void setdata()
{
cout<<"Enter a number"<<endl;
cin>>a;
}
friend void max(Class1,Class2);
};
class Class2
{
int a;
public:
void setdata()
{
cout<<"Enter a number"<<endl;
cin>>a;
}
friend void max(Class1,Class2);
};
void max(Class1 c1, Class2 c2)
{
if(c1.a>c2.a)
{
cout<<"Larger= "<<c1.a;
} else {
cout<<"Larger= "<<c2.a;
}
}
int main()
{
Class1 x;
Class2 y;
[Link]();
[Link]();
max(x,y);
}
7.3 Function Overloading
• Function that shares the same name are said to be overloaded functions and the process is
referred to as function overloading. i.e., function overloading is the process of using the
same name for two or more functions.
• Overloaded functions can help reduce the complexity of a program by allowing related
operations to be referred to by the same name.
• Each redefinition of a function must use different type of parameters(arguments), or
different sequence of parameters or different number of parameters. The number, type or
sequence of parameters for a function is called the function signature.
• When we call the function, appropriate function is called based on the parameter passed.
Two functions differing only in their return type cannot be overloaded.
• For e.g.- int add(int, int) and float add(int, int)
• A function call first matches the declaration having the same number and type of arguments
and then calls the appropriate function for execution. A best match must be unique. The
function selection will involve the following steps:
✓ the compiler first tries to find an exact match in which the types of actual arguments
are the same and uses that function
✓ if an exact match is not found, the compiler uses the integral promotion to the actual
parameters, such as,
✓ char to int
✓ float to double to find the match
✓ if both of the above fails, the compiler tries to use the built-in conversions and then
uses the function whose match is unique.
• Example 1:
#include <iostream>
using namespace std;

int add(int, int);


double add(double, double);

int main( )
{
cout<<"The output is: "<<add(10,20)<<endl;
cout<<"The output is: "<<add(10.70,20.10)<<endl;
return 0;
}
int add(int a, int b)
{
return(a+b);
}
double add(double a, double b)
{
return(a+b);
}

• Example 2:
#include <iostream>
using namespace std;
int area(int) ; // function area with int return type
double area(double, int) ; // function area with double return type
long area(long, int, int) ; // function area with long return type

int main( )
{
cout<<area(10)<<endl;
cout<<area(2.5,8)<<endl;
cout<<area(100,75,15)<<endl;
return 0 ;
}
int area(int s) // square
{
return(s*s) ;
}
double area(double r, int h) // Surface area of cylinder ;
{
return(2*3.14*r*h) ;
}
long area(long l, int b, int h) //area of parallelopiped
{
return(2*(l*b+b*h+l*h)) ;
}
7.4 Inheritance
• Inheritance is the most powerful feature of object-oriented programming.
• Inheritance is the process of creating new classes, called derived classes, from existing
classes or base classes. The class inherits all the capabilities of the base class but can add
refinements of its own.
• When new class is created based on some other class using inheritance, the newly created
class is called the derived class or sub-class, while the class on which it is based is called
base class or superclass.
✓ Sub-Class: The class that inherits properties from another class is called Sub class
or Derived Class.
✓ Super-Class: The class whose properties are inherited by sub class is called Base
Class or Super class.
• The derived class inherits some or all the traits from base class. The base class is unchanged
by this. Most important advantage of inheritance is re-usability. Once a base class is written
and debugged, it need not be touched again and we can use this class for deriving another
class if we need. Reusing existing code saves time and money. By re-usability a
programmer can use a class created by another person or company and without modifying
it derive other class from it.
• Syntax:
class subclass_name : access_mode base_class_name
{
//body of subclass
};

Why and when to use inheritance?


Consider a group of vehicles.
We need to create classes for Bus, Car and Truck. The methods fuelAmount(), capacity(),
applyBrakes() will be same for all of the three classes. If we create these classes avoiding
inheritance then we have to write all of these functions in each of the three classes as shown in
below:
We can clearly see that above process results in duplication of same code 3 times. This increases
the chances of error and data redundancy. To avoid this type of situation, inheritance is used. If
we create a class Vehicle and write these three functions in it and inherit the rest of the classes
from the vehicle class, then we can simply avoid the duplication of data and increase re-
usability.

Purpose of Inheritance
• Code Reusability
• Method Overriding (Hence, Runtime Polymorphism.)
• Use of Virtual Keyword
Advantages of Inheritance
• Inheritance promotes reusability. When a class inherits or derives another class, it can
access all the functionality of inherited class.
• Reusability enhanced reliability. The base class code will be already tested and debugged.
• As the existing code is reused, it leads to less development and maintenance costs.
• Inheritance makes the sub classes follow a standard interface.
• Inheritance helps to reduce code redundancy and supports code extensibility.
• Inheritance facilitates creation of class libraries
Disadvantages of Inheritance
• Inherited functions work slower than normal function as there is indirection.
• Improper use of inheritance may lead to wrong solutions.
• Often, data members in the base class are left unused which may lead to memory wastage.
• Inheritance increases the coupling between base class and derived class. A change in base
class will affect all the child classes
Example of Inheritance
// C++ program to demonstrate implementation of Inheritance
#include <iostream>
using namespace std;

//Base class
class Parent
{
public:
int id_p=9;
};

// Sub class inheriting from Base Class(Parent)


class Child: public Parent
{
public:
int id_c=8;
};

//main function
int main ()
{
Child obj1;
cout << "Child id is " << obj1.id_c << endl;
cout << "Parent id is " << obj1.id_p << endl;
return 0;
}

Inheritance Visibility Mode


Depending on Access modifier used while inheritance, the availability of class members of Super
class in the sub class changes. It can either be private, protected or public.
Public mode:
If we derive a sub class from a public base class. Then the public member of the base class will
become public in the derived class and protected members of the base class will become protected
in derived class.
Protected mode:
If we derive a sub class from a Protected base class. Then both public member and protected
members of the base class will become protected in derived class.
Private mode:
If we derive a sub class from a Private base class. Then both public member and protected members
of the base class will become Private in derived class.

// C++ Implementation to show that a derived class doesn’t inherit access to private data
members. However, it does inherit a full parent object
class A
{
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A
{
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A
{
// x is protected
// y is protected
// z is not accessible from C
};
class D : private A // 'private' is default for classes
{
// x is private
// y is private
// z is not accessible from D
};
Types of Inheritance
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance

1. Single Inheritance
• In single inheritance, a sub-class is derived from only one super class.
• It inherits the properties and behavior of a single-parent class. Sometimes, it is also known
as simple inheritance.
• Syntax:
class A // base class
{
private:
{
…. // body part

}
public:
{
…..// body part
…..
}
};
class B : public A // derived class B
{
……
…..
};
• Example 1:
#include <iostream>
using namespace std;

class Vehicle {
public:
Vehicle() {
cout << "This is a Vehicle" << endl;
}
};
class Car : public Vehicle {
public:
Car() {
cout << "This Vehicle is Car" << endl;
}
};

int main() {

Car obj;
return 0;
}
• Example 2: A class Room consists of two fields length and breadth and method int area()
to find the area of room. A new class BedRoom is derived from class Room and consist of
additional field height and two methods setData(int,int,int) to set the value for three fields
and int volume() to find the volume. Now write the C++ program to input the length
,breadth and height and find the area and volume.
#include<iostream>
using namespace std;
class Room
{
protected:
float length, breadth;
public:
int area()
{
return(length*breadth);
}
};
class BedRoom : public Room
{
private:
float height;
public:
void setData(int l, int b, int h)
{
length=l;
breadth=b;
height=h;
}
int volume()
{
return(length * breadth * height);
}
};
int main()
{
BedRoom b;
[Link](3,4,5);
cout<<"Area of bedroom= "<<[Link]()<<endl;
cout<<"Volume of bedroom="<<[Link]();
}
2. Multiple Inheritance
• In Multiple inheritance, one class can have more than one superclass and inherit features
from all parent classes.
• Syntax:
class A
{
…….
……
};
class B
{
…….
……
};
class C : public A, public B, public …n
{
…….
……
};
• Here two base classes A and B have been created and a derived class C is created from
both base classes.
• Example 1:
#include <iostream>
using namespace std;

class LandVehicle
{
public:
void landInfo()
{
cout << "This is a LandVehicle" << endl;
}
};

class WaterVehicle
{
public:
void waterInfo()
{
cout << "This is a WaterVehicle" << endl;
}
};

// Derived class inheriting from both base classes


class AmphibiousVehicle : public LandVehicle, public WaterVehicle
{
public:
AmphibiousVehicle()
{
cout << "This is an AmphibiousVehicle" << endl;
}
};

int main()
{
AmphibiousVehicle obj;

[Link]();
[Link]();
return 0;
}
• Example 2: Create two classes class1 and class2 each having data member for storing a
number, a method to initialize it. Create a new class class3 that is derived from both class
class1 and class2 and consisting of a method that displays the sum of two numbers from
class1 and class2.
#include<iostream>
using namespace std;
class class1
{
protected:
int n;
public:
void getn(int p)
{
n=p;
}
};
class class2
{
protected:
int m;
public:
void getm(int q)
{
m=q;
}
};
//Derived class
class class3: public class1, public class2
{
public:
void displaytotal()
{
int tot;
tot=n+m;
cout<<"Sum ="<<tot;
}
};
int main()
{
class3 a;
[Link](4);
[Link](5);
[Link]();
}
3. Multilevel Inheritance
• Multilevel inheritance in C++ means a class is derived from another derived class, forming
a chain of inheritance.
• Syntax:
class A
{
//member of A
}
class B :public/private/protected A
{
//own member of B
}
class C :public/private/protected B
{
//own member of C
}
• In above case, class B is derived from Class A while class C is derived from derived class
B. So, the class A serves as base class for B and B serves as base class for C therefore B is
also called as intermediate class because it provides a link between class A and C.
• Example 1:
#include <iostream>
using namespace std;

class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};

// Derived class from Vehicle


class FourWheeler : public Vehicle
{
public:
FourWheeler()
{
cout << "4 Wheeler Vehicles" << endl;
}
};

// Derived class from FourWheeler


class Car : public FourWheeler
{
public:
Car()
{
cout << "This 4 Wheeler Vehicle is a Car" << endl;
}
};

int main()
{
Car obj;
return 0;
}
• Example 2: A class Student consists of field roll, a method to assigns roll number. A new
class Test is derived from class Student and consists of two new fields sub1 and sub2, a
method to initialize these fields with obtained mark. Again, a new class Result is derived
from Test and consists of a field total and a method to display entire details along with total
obtained marks. WAP to input roll number, marks in two different subject and display total.
#include<iostream>
using namespace std;
class Student
{
protected:
int roll;
public:
void setroll(int r)
{
roll=r;
}
};
class Test: public Student
{
protected:
float sub1, sub2;
public:
void setmark(float m1, float m2)
{
sub1=m1;
sub2=m2;
}
};
class Result : public Test
{
private:
float total;
public:
void display()
{
total=sub1+sub2;
cout<<"Roll number= "<<roll<<endl;
cout<<"Mark in first subject= "<<sub1<<endl;
cout<<"Mark in second subject= "<<sub2<<endl;
cout<<"Total= "<<total;
}
};
int main()
{
int r;
float s1,s2;
cout<<"Enter roll number"<<endl;
cin>>r;
cout<<"Enter marks in two subject"<<endl;
cin>>s1>>s2;
Result res;
[Link](r);
[Link](s1,s2);
[Link]();
}
Function Overriding
• In C++, a base class member can be overridden by defining a derived class member with
the same name as that of the base class member.
• Function overriding is an object-oriented concept in which a derived (child) class provides
its own implementation of a function that already exists in the base (parent) class, using
the same function name, same parameters, and same return type.
• It supports runtime polymorphism.
• Example:
#include<iostream>
using namespace std;
class Abase //Base class
{
public:
void show()
{
cout<<”I am Base class.”<<endl;
}
};
class Bderived : public Abase //Derived class
{
public:
void show()
{
cout<<”I am Derived class”<<endl;
}
};
int main()
{
Bderived Bobj;
[Link]();

//To show value of base class


[Link]::show();
}
• Here, the function show() is overridden.
✓ If the function is invoked from an object of the derived class, then the function in
the derived is executed.
✓ If the function is invoked from an object of the base class, then the base class
member function is invoked.
7.6 Template Function

What is template?
• Templates are the foundation of generic programming, which involves writing code in a
way that is independent of any type.
• A template is a blueprint or formula for creating a generic class or a function.
• A template is one of the recently added feature in C++. It supports the generic data types
and generic programming.
• Generic programming is an approach where generic data types are used as parameters in
algorithms so that they can work for a variety of suitable data types.
Example:
✓ A class template for an array class would enable us to create arrays of various data
types such as int, array and float array.
✓ A function template say mul() can be used for multiplying int, float and double type
values.
• A Template can be considered as Macro. When an object of specific type is defined for
actual use, the template definition for that class is substituted with the required data type.
• Since a template is defined with a parameter that would be replaced by a specified data
type at the time of actual use of the class or function, the template is also called as
parametrized class or functions.

Features of Template
• Templates are easier to write. We can create only one generic version of our class or
function instead of manually creating specializations.
• Templates are easier to understand, since they provide a straightforward way of abstracting
type
• information.
• Templates are type safe. Because the types that templates act upon are known at compile
time, the compiler can perform type checking before errors occur.
What is template function?
• In C++, function overloading allows to define multiple functions with the same names but
with different arguments.
• In a situation, where we need to define functions with the same body but of different data
type, we can use function overloading. But while overloading a function, different
data types will need different functions, and hence the function needs to be rewritten
several times for each data type. This is time consuming and space consuming. So, C++
introduced the new concept of function template.
• Function template are special functions that can operate with generic types. It is the
function which is written just for once, and have it worked for many different data types.
• The key innovation in function templates is to represent the data type used by the function
not as a specific type such as int, float, etc., but as a name that can stand for any type.
• The general format for function template is given below:
template<class T> or template<typename T>
returnType of type Tfunction_name (argument of type T)
{
//body of function with type T whenever appropriate
}
Note: Main function can’t be declared as template
• The template keyword signals the compiler that we’re about to define a function template.
The keyword class, with angle brackets, acts as the type. We can define our own data type
using classes, so there’s no distinction between types and classes. The variable following
keyword class (‘T’ in above syntax) is called the template argument.

Example:

1. #include <iostream>
using namespace std;
template <class T1> or template <typename T1>
// In templates, the keyword class is used to declare a generic data type. It does not
mean a C++ class; it simply tells the compiler that T represents a type.
T1 sum (T1 a, T1 b)
{
return (a+b);
}
int main()
{
cout << sum(10, 20) << endl;
cout << sum(11.5, 13.1) << endl;
return 0;
}

Output:
30
24
In the above example, sum() is a template function. It takes two arguments of T1 type and
returns a T1 type data equal to the sum of two arguments. Defining a function as a template
doesn’t generate code for different types; it is just a message to the compiler that the
function can be called with different data types. Thus, in main(), when sum(10, 20) is
called, the template generates a function by substituting the template argument (T1) with
int. This is called instantiating the function template, and each instantiated version of the
function is called a template function.
When sum(11.5, 13.1) is invoked, instantiation of the template by float takes place and
another template function of float type is created.
Note: The compiler generates only one version of the function for each data type.

2. WAP to declare template function that can be used to find the area of rectangle.
#include<iostream>
using namespace std;
template<class t>
t area(t len, t bre)
{
return(len*bre);
}
int main()
{
int l1=6, b1=4;
cout<<"Area= "<<area(l1, b1)<<endl;
float l2=2.5, b2=2.0;
cout<<"Area= "<<area(l2, b2);
}
3. Function Template to Find Maximum of Two Numbers
#include <iostream>
using namespace std;

template <class T>


T maximum(T a, T b)
{
if (a > b)
return a;
else
return b;
}

int main()
{
cout << maximum(10, 20) << endl;
cout << maximum(12.5, 9.8) << endl;
cout << maximum('A', 'Z') << endl;

return 0;
}
4. WAP to declare a function template that can be used to swap two values of a given type of data.
//using concept of pointer

#include <iostream>
using namespace std;
template<class T >
void swap( T *fn, T *sn )
{
T tmp;
tmp=*fn;
*fn=*sn;
*sn=tmp;
}
int main()
{
int m=5,n=6;
cout<<"Before swapping"<<endl;
cout<<"M= "<<m<<endl<<"N= "<<n<<endl;
swap(&m,&n);
cout<<"After swapping"<<endl;
cout<<"M= "<<m<<endl<<"N= "<<n<<endl;
}

//Using concept of reference variable


#include <iostream>
using namespace std;
template<class T >
void swap( T &fn, T &sn )
{
T tmp;
tmp=fn;
fn=_sn;
fn=tmp;
}
int main()
{
int m=5, n=6;
cout<<"Before swapping";
cout<<"M= "<<m<<endl<<"N= "<<n<<endl;
swap(m,n);
cout<<"After swapping";
cout<<"M= "<<m<<endl<<"N= "<<n<<endl;
}
Function template with multiple parameters
• Like template class, we can use more than one generic data type in the template
statement, using a comma separated list as shown below.
template<class t2, class t2.........>
Return_typefunction_name(arguments of types T1, T2........)
{
// body of function
}
• Example:
#include <iostream>
using namespace std;
template<class T1, class T2 >
void show (T1 x, T2 y)
{
cout<<"First Parameter= "<<x<<endl;
cout<<"Second Parameter= "<<y<<endl;
}
int main()
{
show(1,2);
show(1.4,3.5);
show('r',"Ram");
}
7.7 Exception Handling
Introduction to error
• In computing, an error in a program is due to the code that does not conform to the order
expected by the programming language.
• An error may produce and incorrect output or may terminate the execution of program
abruptly or even may cause the system to crash.
Types of Errors
i. Compile Time Error
ii. Runtime Error

Compile Time Error


• At compile time, when the code does not comply with the C++ syntactic and semantics
rules, compile-time errors will occur.
• The goal of the compiler is to ensure the code is compliant with these rules. Any rule-
violations detected at this stage are reported as compilation errors. These errors are
checked.
• The following are some common compile time errors:
➢ Writing any statement with incorrect syntax
➢ Using keyword as variable name
➢ Attempt to refer to a variable that is not in the scope of the current block
➢ A class tries to reference a private member of another class
➢ Trying to change the value of an already initialized constant (final member)
etc..........
Runtime Error
• When the code compiles without any error, there is still chance that the code will fail at run
time. The errors only occur at run time are call run time errors.
• Run time errors are those that passed compiler’s checking, but fail when the code gets
executed. These errors are unchecked.
• The following are some common runtime errors:
➢ Divide by zero exception
➢ Array index out or range exception
➢ Stack Overflow exception
➢ Dereferencing of an invalid pointer etc..........
• So, runtime errors are those which are generally can’t be handled and usually refers
catastrophic failure.

Exception
• An exception is a run-time error. Proper handling of exceptions is an important
programming issue. This is because exceptions can and do happen in practice and programs
are generally expected to behave gracefully in face of such exceptions.
• Unless an exception is properly handled, it is likely to result in abnormal program
termination and potential loss of work. For example, an undetected division by zero or
dereferencing of an invalid pointer will almost certainly terminate the program abruptly.
Types
i. Synchronous: Exception that are caused by events that can be control of program is
called synchronous exception. Example, array index out or range exception.
ii. Asynchronous: Exception that are caused by events beyond the control of program is
called synchronous exception. Example, Exception generated by hardware
malfunction.

Basic Steps in exception handling


• The purpose/Use of exception handling mechanism is to provide means to detect and report
an exception so that appropriate actions can be taken. Exception handling mechanism in
C++ consists of four things:
i. Detecting of a run-time error (Hit the exception)
ii. Raising an exception in response to the error (Throw the exception)
iii. Receive the exception information (Catch the exception)
iv. Taking corrective action. (Handle the exception)
• C++ provides a language facility for the uniform handling of exceptions.
• Under this scheme, a section of code whose execution may lead to run-time errors is labeled
as a try block.
• Any fragment of code activated during the execution of a try block can raise an exception
using a throw clause. All exceptions are typed (i.e., each exception is denoted by an object
of a specific type).
• A try block is followed by one or more catch clauses. Each catch clause is responsible for
the handling of exceptions of a particular type. When an exception is raised, its type is
compared against the catch clauses following it.
• If a matching clause is found, then its handler is executed. Otherwise, the exception is
propagated up, to an immediately enclosing try block (if any). The process is repeated until
either the exception is handled by a matching catch clause or it is handled by a default
handler.

• The general form is as below:


try
{
.....
.....
throw exception; //block of statements which detect and throws an
exception
}
catch (type arg) //catches exception
{
.....
.... //block of statements that handle the exception
.....
}
Example:
1) WAP to input two number and divide first number by second. The program must handle the
divide by zero exception.
#include<iostream>
using namespace std;
int main()
{
int nu,de,res;
cout<<"Enter numerator and denominator"<<endl;
cin>>nu>>de;
try
{
if(de==0)
{
throw(de); //throw int object
}
else
{
res=nu/de;
cout<<"Result= "<<res;
}
}
catch(int i) //catches the int type exception
{
cout<<"Divide by zero exception occurred: de= "<<i;
}
}
So, in the above program, when no exception is thrown, the catch block is skipped and outputs
correct result. But when the user input zero for denominator, the exception is thrown using throw
statement with int type object as argument. Since the exception object type is int, the exception
handler i.e., catch statement containing int type argument catches the exception and handles it by
displaying necessary message or performing necessary steps further.
Note:
✓ During execution, when throw statement is encountered, then it immediately transfers the
control suitable exception handler i.e., catch block. Hence all the statement after throw in
try block are skipped.
✓ If there are multiple catch block with integer type argument, then the first one immediately
after try block gets executed.
✓ When an exception object is thrown and none of the catch block matches, the program is
aborted with the help of abort() function which is invoked automatically.
2) WAP to find square root with exception handling mechanisms.
Invoking functions that generates Exception
• Exceptions can also be thrown from function that are invoked from within the try block.
The point at which throw is executed is called throw point. Once an exception is thrown
to the catch block, control can’t return to the throw point.
• The general form is:
typefunction_name(arg list) // Function with exception
{
Throw (object); // throws an exception
}
..........
..........
try
{
............
............ // function is invoked from here
.............
}
catch(type org) //caches exception
{
............
............ //handles the exception here
............
}
• Example 1:
#include<iostream>
using namespace std;
int divide(int,int);
int main()
{
int nu,de,res;
cout<<"Enter numerator and denominator"<<endl;
cin>>nu>>de;

try
{
res=divide(nu,de);
cout<<"Result= "<<res;
}
catch(int i) //catches the int type exception
{
cout<<"Divide by zero exception occurred: de= "<<i;
}
}
int divide(int fn, int sn)
{
if(sn==0)
{
throw(sn);
}
else
{
return(fn/sn);
}
}
• Example 2:
Other Examples:
1.

2.
3. WAP to input two numbers and divide first number by second. The result must be stored in the
index entered by user.
4.

(For more visit: [Link] )

You might also like