You are on page 1of 48

JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE

Object Oriented Programming

TABLE OF CONTENTS

COURSE OUTCOME 2
Syllabus 2

UNIT - 1 3
Cout and Cin 3
Function 5
Passing arguments in function 5
Features of Object Oriented Programming 6
Scope Resolution Operator 8
For defining member functions of class outside the class 8
To access the global version of a variable 9

UNIT - 2 10
Constructor 10
Properties of Constructor 10
Types of constructor 10
Destructor 12
Properties of Destructor 12
Function Overloading 13
Passing Object as Function Argument 14
Friend Function 16
Inline Function 17

UNIT - 3 19
Inheritance 19
Protected class member 21
Access Specifiers (visibility modes) 22
Ways of inheritance: public, private, protected 22
Pointer to Object 24
Virtual Function 25

UNIT - 4 27
Operator Overloading 27
Overloading Binary Operators Using Friend Function 31

UNIT - 5 32
Template 32
Function Template 32

Amit Mithal, Department of Computer Science and Engineering Page no: 1 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
Types of Errors 33
Types of Exceptions 34
Exception Handling Mechanism in C++ 34
Multiple Throw and Multiple Catch 36
Multiple Throw and Single Catch (Generic catch) 39
Rethrowing an Exception 40
Specifying Exceptions 42
File Handling 44

QUESTION BANK 45

A Note For Students 46

List of Books 46
Text Book 46
Reference Books 47

CO-WISE WEAK STUDENT ASSIGNMENT 47


Weak Student in CO1- Assignment 47
Weak Student in CO2- Assignment 47
Weak Student in CO3- Assignment 47

CO-WISE STRONG STUDENT ASSIGNMENT 48

COURSE OUTCOME
After completion of this course, students will be able to:

CO1: Identify and analyze Object Oriented Programming concepts in designing solution of a problem.

CO2: Apply constructor, friend function and class when analyzing a problem statement.

CO3: Apply and analyze features of inheritance and polymorphism for developing solution of a complex
problem.

CO4: Identify and handle exceptions in an object oriented program. Perform generic programming using
templates.

Syllabus
UNIT-1:

Amit Mithal, Department of Computer Science and Engineering Page no: 2 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
Introduction to different programming paradigm, characteristics of OOP, Class, Object, data
member, member function, structures in C++, different access specifiers, defining member
function inside and outside class, array of objects.

UNIT - 2:
Concept of reference, dynamic memory allocation using new and delete operators, inline
functions, function overloading, function with default arguments, constructors and destructors,
friend function and classes, using this pointer.

UNIT - 3:
Inheritance, types of inheritance, multiple inheritance, virtual base class, function overriding,
abstract class and pure virtual function

UNIT - 4:
Constant data member and member function, static data member and member function,
polymorphism, operator overloading, dynamic binding and virtual function

UNIT - 5
Exception handling, Template, Stream class, File handling

UNIT - 1

C++ is a type of programming language, developed by Bjarne Stroustrup.

Cout and Cin

cout in C++, is similar to printf in C. cout is used to display some message on the screen. cout
can be used as:

cout<<”Hello World”;

This statement will display the message “Hello World” on the screen.

Amit Mithal, Department of Computer Science and Engineering Page no: 3 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
cin in C++, is similar to scanf in C. cin is used to take input the value of some variable from the
user. cin can be used as:

cin>>x;

This statement can be used to take input the value of some variable x from the user. The data
type of x can be int, float, char etc. There is no format specifier %d, %f, %c in cin (although
format specifier was present in scanf).

We have to use the header file iostream.h, for cout and cin.

Ques: Write a program in C++ to display a message “Hello World on the screen.
Solution:
#include<iostream.h>
#include<conio.h>
void main()
{
cout<<”Hello World”;
}

Output:
Hello World

Ques: Write a program in C++ to take as input, the value of two integers, from the user. Find
and display the addition of these two integers.
Solution:
void main()
{
int x,y,z;
cin>>x; //Input x
cin>>y; //Input y
z = x + y;
cout<<”Sum = “;
cout<<z;
}
Output:
10
20
Sum = 30

Amit Mithal, Department of Computer Science and Engineering Page no: 4 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
Function

When we classify our program into various functions, then our program becomes more readable
and easier to understand.

Ques: Write a program in C++ to find the area of rectangle by using a function named as fun().
Solution:
void main()
{
fun(); //calling of function fun
}

void fun()
{
int l,b,area;
cin>>l;
cin>>b;
area = l*b;
cout<<area;
}

Output:
10
20
200

Passing arguments in function

The advantage of passing arguments or parameters in a function is that there is a


communication of data from calling function to called function.

Ques: Write a program in C++ to find the area of rectangle by passing arguments in a function
named as fun(int,int).
Solution:
void main()
{
fun(10,20); //10 and 20 are arguments of function fun
}

Amit Mithal, Department of Computer Science and Engineering Page no: 5 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
void fun(int l,int b)
{
int area;
area = l*b;
cout<<area;
}

Output:
200

Features of Object Oriented Programming

1) Class & Object

Class is a logical entity while object is a physical entity. Class is like a user defined data type.
Object take up space in memory. For example, the room in which we are sitting is a class and
the objects of this class are black-board, chalk, tables, chairs, fans etc.

A class in C++ has two types of members: data members and function members. (Just like in
the classroom in which we are sitting, there are two types of members: student member and
faculty member). Generally, we put data members in private section of a class and function
members in public section of class.

● Whatever we write under private section of a class, can be accessed only within the
class and not outside the class.
● Whatever we write under public section of a class, can be accessed from both within the
class and outside the class.

2) Encapsulation

The wrapping up of data members and function members together inside a single unit, called as
class is called as encapsulation.

3) Polymorphism

Poly means many and morphism means forms. The ability to take more than one form is called
as polymorphism. There are two types of polymorphism:

Amit Mithal, Department of Computer Science and Engineering Page no: 6 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
● Compile time polymorphism (can be achieved using function overloading and operator
overloading)
● Run time polymorphism (can be achieved using virtual function)

4) Data Hiding

The data member of a class should be hidden from outside the class. This can be achieved if
we put data member under private section of a class. This is because whatever we write under
private section can be accessed within the class only and not outside the class.

5) Dynamic Binding

The binding up of the function call with its code at run time is called as dynamic binding.

6) Message Passing

The communication of data from calling function to called function, in the form of arguments
passed to the function, is called as message passing.

7) Data Abstraction

Showing only the data which is required and hiding the unnecessary background details is
called as data abstraction.

8) Inheritance

The ability of one class (called as child class or derived class), to acquire properties from
another class (called as parent class or base class), is called as inheritance. The following are
the types of inheritance:

i) Single inheritance
ii) Multiple inheritance
iii) Multilevel inherirtance
iv) Hierarchical inheritance
v) Hybrid inheritance

Example of class & object

class abc
{

Amit Mithal, Department of Computer Science and Engineering Page no: 7 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
private:
int x; //member data of class abc is x
public:
void fun() //member function of class abc is fun
{
x=10;
cout<<x;
}
}; //class closed

void main()
{
abc ob; //ob is object of class abc
ob.fun(); //member function fun of class abc is called using object ob of class abc
}

Output: 10

Scope Resolution Operator


Scope Resolution Operator, denoted by the symbol :: (double colon) has two uses:
i) For defining member functions of class outside the class
ii) To access the global version of a variable

For defining member functions of class outside the class


We can define member function of a class outside the class definition using scope resolution
operator (denoted as double colon sign ::)

Example of defining member function outside class

class abc
{
public:
void fun(); //member function of class abc
}; // class definition closed

void abc::fun() //member function fun of class abc is defined outside class definition

Amit Mithal, Department of Computer Science and Engineering Page no: 8 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
{
cout<<"hello";
}
void main()
{
abc ob;
ob.fun(); //member function fun called
}

To access the global version of a variable

Second use of scope resolution operator is to access the global version of a variable (this
cannot be done in C). For example ::count means the global version of the variable count (and
not the local variable count declared in that block)

Example of :: to access global version of a variable

#include<iostream.h>
#include<conio.h>
int m=10; //global m
void main()
{
clrscr();
int m=20; //m redeclared, local to main
{
int k=m;
int m=30; //m declared again,this time, local to inner block
cout<<"We are in inner block\n";
cout<<"k = "<<k<<"\n";
cout<<"m = "<<m<<"\n";
cout<<"::m = "<<::m<<"\n";
}
cout<<"\nWe are in outer block\n";
cout<<"m = "<<m<<"\n";
cout<<"::m = "<<::m<<"\n";
getch();
}

Output:

Amit Mithal, Department of Computer Science and Engineering Page no: 9 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
We are in inner block
k = 20
m = 30
::m = 10

We are in outer block


m = 20
::m = 10

UNIT - 2
Constructor
A constructor is used to initialize the data member of a class. There are three types of constructor:

Properties of Constructor
1) The name of constructor is same as that of class name.
2) Constructor does not have any return type, not even void.
3) Constructor is always declared in the public section of the class.
4) Constructor is called automatically, as soon as object of the class is created.

Types of constructor
● Default constructor
● Parameterized constructor
● Copy constructor

● A constructor having zero arguments is called as default constructor.


● A constructor that passes one or more number of arguments is called as parameterized
constructor.

Example of constructor

class abc
{

Amit Mithal, Department of Computer Science and Engineering Page no: 10 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
private:
int x;
public:
abc() //constructor defined
{
x = 10; //private data member initialized
cout<<x;
}
};
void main()
{
abc ob; //constructor called
}

Output:
10

Example of parameterized constructor

class abc
{
private:
int x;
public:
abc(int x1)
{
x=x1;
cout<<x;
}
};
void main()
{
abc ob(10);
}

Output: 10

There are two ways of calling a constructor: i) implicit calling of constructor ii) explicit calling of
constructor. In the above program, the statement abc ob(10); is implicit calling of constructor. This
statement can also be written as abc ob = abc(10); This is explicit calling of constructor. Both

Amit Mithal, Department of Computer Science and Engineering Page no: 11 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
implicit and explicit calling of constructor achieves the same effect, but the difference is that
implicit constructor calling is compact than explicit constructor calling.

Destructor
A destructor is used to destroy objects i.e. destructor frees up the memory space occupied by the
objects of the class.

Properties of Destructor
1) Destructor has the same name as class name, but it is preceded by tilde (~) sign.
2) Destructor releases the memory space occupied by the objects of a class, at the time of
program termination.
3) Destructor is called automatically, at the time of program termination.

Example of destructor

class abc
{
private:
int x;
public:
abc(int x1) //parameterized constructor
{
x = x1;
cout<<x;
}

~abc() // destructor
{
cout<<”\nDestructor called”;
}
};

void main()
{
abc ob(10); //parameterized constructor called- ob’s x will be set to 10
}// destructor called at program termination

Output:

Amit Mithal, Department of Computer Science and Engineering Page no: 12 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
10
Destructor called

Function Overloading
● Doing something in excess is called as overloading.
● When a function is defined more than one time such that either the number of arguments
passed in the functions differ or the data type of arguments passed in the functions differ
or both, then this is called function overloading. Function overloading is used to achieve
compile time polymorphism.

Example of Function Overloading

class abc
{
private:
int x,y,s;
void fun(int x1,int y1) //fun defined
{
x = x1; y = y1;
cout<<x*y<<endl;
}
void fun(int s1) //fun redefined - fun is overloaded
{
s = s1;
cout<<s*s;
}
};
void main()
{
abc ob1;
ob1.fun(2,3);
ob1.fun(4);
}

Output:
6
16

Constructor Overloading

Amit Mithal, Department of Computer Science and Engineering Page no: 13 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming

When a constructor is defined more than one time such that i) the number of arguments passed
in the constructors differ or ii) the data type of arguments passed in the constructors differ or both
i) and ii) holds true, then this is called as constructor overloading.

Example of Constructor Overloading

class abc
{
private:
int x,y,s;
abc(int x1,int y1) //constructor defined
{
x = x1; y = y1;
cout<<x*y<<endl;
}
abc(int s1) //constructor redefined - constructor is overloaded
{
s = s1;
cout<<s*s;
}
};

void main()
{
abc ob1(2,3);
abc ob2(4);
}

Output:
6
16

Passing Object as Function Argument

We know that in function argument, we can pass variables or constants. Similarly, in function
argument, we can also pass object.

Amit Mithal, Department of Computer Science and Engineering Page no: 14 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming

Example of passing object as function argument

class abc
{
private:
int x;
public:
void set(int x1)
{
x=x1;
}
void show()
{
cout<<x<<“\t”;
}

void fun (abc ob)


{ /*object ob is passed as function argument */
x=x+ob.x;
}
};

void main()
{
abc ob1,ob2;
ob1.set(1);
ob2.set(2);
ob1.fun(ob2); //ob2 is passed as an argument to function fun
ob1.show();
}

Output: 3

/* Question: Write a program in C++ to copy the price of one fruit object into another. Functions:
set (int), show ( ), copy (fruit) to set the price, show the price and copy the price to another
object.
Solution:*/

#include<iostream.h>
#include<conio.h>

Amit Mithal, Department of Computer Science and Engineering Page no: 15 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
class fruit
{
private:
int price;
public:
void set(int price1)
{
price=price1;
}
void show()
{
cout<<price<<endl;
}
void copy(fruit mango1)
{
price=mango1.price;
}
};

void main()
{
clrscr();
fruit mango,apple;
mango.set(100);
mango.show();
apple.copy(mango); //passing object as function argument
apple.show();
getch();
}

/*Output:
100
100*/

Friend Function
● A function which is not a member function of a class, but can still access the private data
member of a class is called as friend function.
● To declare a function as friend, we precede the function name with the keyword friend.

Amit Mithal, Department of Computer Science and Engineering Page no: 16 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
● Friend function may pass an object as its argument

Example of Friend Function

class abc

{
private:
int x;
public:
friend void fun(); //fun function is now friend function of class abc
};
void fun() /*friend function defined outside class without scope resolution operator (::) -
fun is not a member function of class abc*/
{
abc ob;
ob.x=10; //friend function accessing private data member x of class abc
cout<<ob.x;
}
void main()
{
fun(); //friend function called (without object and dot operator)
}
Output: 10

Inline Function

When a function gets called, it takes a lot of extra time in executing instructions for tasks like
jumping to the function, saving registers, pushing arguments into the stack and returning to the
calling function. When a function is small, a substantial percentage of execution time may be
spent in such overheads. To eliminate the cost of calls to small functions, C++ proposes a new
feature called as inline function. An inline function is a function that is expanded in line when it is

Amit Mithal, Department of Computer Science and Engineering Page no: 17 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
invoked. That is, the compiler replaces the function call with the corresponding function code
(something similar to macro expansion. But in macros, usual error checking does not occur during
compilation). To make the function as inline, we precede the function name with the keyword
inline, in the function definition. Inline functions must be defined before they are called.

Example:
inline double cube(double a)
{
return (a*a*a);
}
This inline function can be invoked by statements like
c = cube(3.0);
d = cube(2.5+1.5);

On the execution of these statements, the values of c and d will be 27 and 64 respectively.

Example of inline function

#include<iostream.h>
#include<conio.h>
inline void fun() //inline function must be defined before it is called
{
int a,b;
cin>>a>>b;
cout<<a+b;
}
void main()
{
clrscr();
fun();//inline function called
getch();
}

Output:
10
20
30

The speed benefits of inline functions diminish as the function grows in size. At some point, the
overhead of the function call becomes small compared to the execution of the function, and the

Amit Mithal, Department of Computer Science and Engineering Page no: 18 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
benefits of inline function may be lost. In such cases, the use of normal functions will be more
meaningful. Usually, when a function is small enough to be defined in one or two lines, then such
a function can be made as inline. The inline keyword merely sends a request, not a command, to
the compiler. The compiler may ignore this request if the function definition is too long or too
complicated and compile the function as a normal function.

Some of the situations where inline expansion may not work are:

1. For functions returning values, if a loop, switch or goto exists.


2. For functions not returning values, if a return statement exists.
3. If functions contain static variables.
4. If inline functions are recursive.

Inline expansion makes a program run faster because the overhead of function call and return is
eliminated. However, it makes the program to take up more memory because the statements
that define the inline function are reproduced at each point where the function is called. So, a
trade-off becomes necessary.

UNIT - 3
Inheritance
● The ability of one class, called child class, to acquire properties from another class, called
as parent class is called as inheritance.
● The parent class is also called as base class and child class is also called as derived
class.
● Inheritance is used to achieve reusability of code, which is an important concept of object
oriented programming.

Types of Inheritance

1) Single inheritance: One class is derived from another class.


2) Multiple inheritance: One class is derived from multiple or more than one classes.

Amit Mithal, Department of Computer Science and Engineering Page no: 19 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
3) Multilevel inheritance: One class is derived from another class, which itself is a derived
class of some other class.
4) Hierarchical inheritance: Multiple classes are derived from a single class.
5) Hybrid inheritance: Combination of any 2 or more than 2 types of inheritance.

Parent A B A

Child C
B B C
Single Multiple Hierarchical
inheritance inheritance inheritance

C D
Multilevel
inheritance Hybrid
inheritance

Example of single inheritance

class a //base class or parent class

Amit Mithal, Department of Computer Science and Engineering Page no: 20 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
{
public:
void fun()
{
cout<<“fun”;
}
};
class b:public a //child class or derived class
{ /* public member function fun of base class a inherited in derived class b, so fun() can be called
with b class object */
};
void main()
{
b ob;
ob.fun(); /*fun of class a called with derived class b’s object, as fun is inherited in b class*/
}
Output: fun

Protected class member


● When a class member is declared to be protected, then the protected class member can
be accessed within the class and in the immediately derived class also.
● The visibility of class member as protected is more than private and less than public.

Example of protected class member

class a

{
protected:
int x; /*protected class member x can be accessed in derived class b*/
};

Amit Mithal, Department of Computer Science and Engineering Page no: 21 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
class b : public a
{
public:
void fun()
{
x=10; /*protected class member x accessed in derived
class b*/
cout<<x;
}
};
void main()
{
b ob;
ob.fun();
}

Output: 10

Access Specifiers (visibility modes)


Public, private and protected are called as visibility modes or access specifiers.
Public, private and protected have 2 uses:
a) As class members (already discussed)
b) As a way to derive one class from another

Ways of inheritance: public, private, protected


a) Deriving one class from another, using public visibility mode
class a : public b { }; // a is derived class and b is parent class i.e. class a is derived from class b
In this case of public inheritance, the following will happen:

Amit Mithal, Department of Computer Science and Engineering Page no: 22 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
public → public (i.e public members of base class becomes public members in derived class)
protected → protected (i.e protected members of base class becomes protected members in
derived class)
private → cannot be inherited (i.e private members can NEVER be inherited)

b) Deriving one class from another, using private visibility mode

class a : private b { }; //a is derived class and b is parent class i.e. class a is derived from class b
In this case of private inheritance, the following will happen:

public → private (i.e public members of base class becomes private members in derived class)

protected → private (i.e protected members of base class becomes private members in derived
class)

private → cannot be inherited (i.e private members can NEVER be inherited)

c) Deriving one class from another, using protected visibility mode

class a : protected b { }; //a is derived class and b is parent class i.e. class a is derived from class
b
In this case of protected inheritance, the following will happen:

public → protected (i.e public members of base class becomes protected members in derived
class)

protected → protected (i.e protected members of base class becomes protected members in
derived class)

private → cannot be inherited (i.e private members can NEVER be inherited)


Note that, after inheritance, the visibility of class members (which are inherited) either remains as
it is or visibility decreases and visibility will NEVER INCREASE, in any case.

Let us summarize the above in the form of a table, for a quick glance and better presentation.

Way of inheritance → private protected public


Base class members ↓

private can never be can never be can never be


inherited in derived inherited in derived inherited in derived
class class class

protected becomes private in remains protected in remains protected in


derived class, after derived class, after derived class, after

Amit Mithal, Department of Computer Science and Engineering Page no: 23 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming

inheritance inheritance inheritance

public becomes private in remains protected in remains public in


derived class, after derived class, after derived class, after
inheritance inheritance inheritance

Pointer to Object
A member function of a class can also be called with the help of pointer to object. We use →
(arrow) operator to call the member function of a class, using pointer to object or object pointer.

Example of pointer to object

#include<iostream.h>
#include<conio.h>
class abc
{
public:
void fun()
{
cout<<"a";
}
};
void main()
{
clrscr();
abc *obptr; //obptr is object pointer or pointer to object
obptr->fun(); //fun function called using pointer to object
getch();
}

Output: a

Amit Mithal, Department of Computer Science and Engineering Page no: 24 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming

Virtual Function
● A virtual function is a function which is defined in base class and redefined in derived
class. So, virtual function is taking more than one form (polymorphism).
● To declare a function as virtual, we precede the function name (in the base class version)
with the keyword virtual.
● Virtual function is used to achieve Run Time Polymorphism in C++.
● Virtual function is called with the help of pointer to object of base class. It depends on the
contents of pointer to object of base class, as to which version of virtual function will be
called- either of base class or of derived class. If pointer to object of base class contains
address of base class object and then virtual function is called, then virtual function of
base class will be called. Secondly, if pointer to object of base class contains address of
derived class object and then virtual function is called, then virtual function of derived class
will be called. The contents of pointer to object is checked at run time, so we say that
virtual function is used to achieve Run Time Polymorphism in C++. Virtual function is called
with the help of pointer to object of base class and using → (arrow) operator. This concept
is illustrated in the following example:

Example of Virtual Function


class a
{
public:
virtual void fun()
{
cout<<“a\t“;
}
};
class b:public a
{
public:
void fun()
{

Amit Mithal, Department of Computer Science and Engineering Page no: 25 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
cout<<“b”;
}
};

void main()

{
a *ptr,ob1;
b ob2;
ptr=&ob1;
ptr → fun();
ptr = &ob2;
ptr → fun();
}
Output: a b

Pure virtual function

● A pure virtual function is a function which has no body in the base class and that function
is defined in the derived class.
● Syntax to declare pure virtual function:

virtual void base_class_function() = 0; (in base class definition)

Example of pure virtual function


class a
{
public:
virtual void fun()=0;
};
class b:public a
{
public:
void fun()

Amit Mithal, Department of Computer Science and Engineering Page no: 26 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
{
cout<<“b”;
}
};

void main()

{
a *ptr;
b ob2;
ptr=&ob2;
ptr → fun();
}
Output: b

UNIT - 4
Operator Overloading

● Doing something in excess is called as overloading.


● When an operator is used to operate on objects, in addition to constants and variables,
then this is called as operator overloading.

Types of operators

i) Unary operator: is an operator which takes only a single operand. In the statement ++ob, where
ob is an object of some class, then ob is the single operand and unary operator is ++.

ii) Binary operator: is an operator which takes two operands. In the statement ob1 + ob2, where
ob1 and ob2 are objects of some class, then ob1 and ob2 are the operands for the binary operator
+.

Amit Mithal, Department of Computer Science and Engineering Page no: 27 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
● Some operators which cannot be overloaded are: sizeof operator, scope resolution
operator ::, conditional operator ?:, member selection operator . (dot)

● Syntax of unary operator overloading:


return_type_of_function operator operator_to_be_overloaded(no object argument);
● Syntax of binary operator overloading:
return_type_of_function operator operator_to_be_overloaded(one object argument);

Example of unary operator overloading

class abc
{
private:
int x;
public:
void set(int x1)
{
x=x1;
}
void show()
{
cout<<x<<“\t”;
}
void operator ++() /*this is called as overloaded operator function*/
{
x=x+1;
}
};

void main()
{
abc ob1;
ob1.set(10);
ob1.show();
ob1++; /*means ob1.++(); overloaded operator function called */
ob1.show();
}

Amit Mithal, Department of Computer Science and Engineering Page no: 28 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming

Output:
10 11

Example of binary operator overloading

class abc
{
private:
int x;
public:
void set(int x1)
{
x=x1;
}

void show()
{
cout<<x<<“\t”;
}

void operator +(abc ob)


{ /*overloaded operator function defined*/
x = x + ob.x; /*This would mean ob1’s x = ob1’s x + ob2’s x */
}
};

void main()
{
abc ob1,ob2;
ob1.set(1);
ob2.set(2);
ob1+ob2; /*This would mean ob1 . + (ob2); overloaded operator function called */
ob1.show();
}

Output: 3

Amit Mithal, Department of Computer Science and Engineering Page no: 29 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
7c) Create a class distance. Make data members as: feet, inches. Define functions as set (int,
int), show ( ). Make 2 objects of class distance. Set and show the values of data members in set
(int, int) and show ( ) functions respectively. Now overload the binary operator + to add these 2
objects using the concept of operator overloading.

Solution:
class distance
{
int feet, inch;
public:
void set(int feet1, int inch1)
{
feet = feet1;
inch = inch1;
}
void show()
{
cout<<feet<<”\t”<<inch<<endl;
}
void operator +(distance d) //overloaded operator function defined
{
feet = feet + d.feet;
inch = inch + d.inch;
}
};
void main()
{
clrscr();
distance d1,d2;
d1.set(1,2);
d2.set(3,4);
d1.show();

d2.show();
d1 + d2; //means d1.+(d2);
d1.show();
getch();
}

Output:
1 2

Amit Mithal, Department of Computer Science and Engineering Page no: 30 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
3 4
4 6

Overloading Binary Operators Using Friend Function


● Friend functions may be used in place of member functions for overloading a binary
operator, the only difference being that a friend function requires two arguments to be
passed, while a member function requires only one. The statement ob3 = ob1 + ob2;
(where ob1, ob2, ob3 are objects of the same class) is equivalent to ob3 = operator
+(ob1,ob2);
● For overloading using statements like ob1 = 2 + ob2; a member function will not work, but
a friend function will work.

Example to overload binary operator using friend function

class abc
{
int x;
public:
void set(int x1)
{
x=x1;
}
void show()
{
cout<<x<<“\t”;
}
friend abc operator +(int,abc);
};

abc operator +(int a,abc ob)


{
abc ob3;
ob3.x = a + ob.x;
return ob3;
}

void main()
{

Amit Mithal, Department of Computer Science and Engineering Page no: 31 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
abc ob1,ob2;
ob1.set(10);
ob1.show();
ob2 = 2 + ob1; /*equivalent to ob2 = operator +(2,ob1); */
ob2.show();
}

Output: 10 12

UNIT - 5
Template
● Template enable us to define generic classes and functions and thus provides support
for generic programming.
● Template is used to achieve reusability of code.
● We can define a single function template, which would be used for addition of two
integers as well as two floats also.

Function Template
The below mentioned program is an example of Function Template.

template <class t>


void fun(t a,t b) /* this is function template. t can be any data type */
{
cout<<a+b<<“\t”;
}
void main()
{
fun(1,2); // function template called, for 2 integers
fun(1.1,2.1); //// function template called, for 2 floats
}
Output: 3 3.2

Explanation: The above program contains a function template, which is used for adding two
numbers (2 integers at one time and two floats at other time). When the function template is
called for the first time, it will add two integers. When the function template is called for the
second time, it will add two float numbers.

Amit Mithal, Department of Computer Science and Engineering Page no: 32 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming

For adding numbers of different data types, say one double and one int, then we have to take
one more template type, in the signature of function template.

Example of Function Template demonstrating multiple(heterogeneous) generic data types

#include<iostream>
using namespace std;
template<class t1,class t2>
void fun(t1 a,t2 b)
{
cout<<a+b<<endl;
}
int main()
{
fun(1,2);
fun(1.4,'a'); // ASCII value of a = 97
}

/*Output:
3 98.4*/

Types of Errors
1) Logic errors
2) Syntactic errors
3) Exceptions

● Logic errors occur due to poor understanding of the problem and solution procedure.
● Syntactic errors occur due to poor understanding of the language itself.
● Run time error is called as an exception.

Examples of exception

1) Divide by zero
2) Accessing array out of bound
3) Running out of memory or disk space

Amit Mithal, Department of Computer Science and Engineering Page no: 33 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
Types of Exceptions
● Synchronous exception
● Asynchronous exception

1) The exceptions that are caused by events under the control of the program are called as
synchronous exceptions.

Example: Divide by zero, Accessing array out of bound, Running out of memory or disk space

2) The exceptions that are caused by events beyond the control of the program are called as

asynchronous exceptions. Example: Keyboard Interrupts.

The exception handling mechanism in C++ is designed to handle only synchronous exceptions.

Exception Handling Mechanism in C++


C++ has a mechanism to handle exceptions. The exception handling mechanism of C++ uses the
following keywords: try, throw and catch.

try is a block which contains statements that may generate exceptions. When an exception is
detected, it is thrown using a throw statement. catch block catches the exception thrown by throw
statement and handles it appropriately. The catch block must immediately follow the try block.

When the try block throws an exception, the program control leaves the try block and enters the
catch statement. Exceptions are objects used to transmit information about a problem. If the type
of object thrown matches the argument type in the catch statement, then catch block is executed
for handling the exception. If they do not match, then the program is aborted. When no exception
is detected and thrown, the control goes to the statement immediately after the catch block, i.e.
the catch block is skipped and execution resumes with the first line after catch.

Most often, try block calls a function that contains an exception. Once an exception is thrown to
the catch block, control cannot return to the throw point. After executing the handler, control goes
to the statement immediately after the catch block.

Note: The try block is immediately followed by the catch block, irrespective of the location of throw
point.

Example of Exception Handling

Amit Mithal, Department of Computer Science and Engineering Page no: 34 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming

void main()
{
int a,b;
cin>>a>>b;
try
{
if(b!=0)
{
cout<<a/b<<"\t";
}
else
{
throw b;
}
}//end of try
catch(int i)
{
cout<<“\tException caught "<<i;
}
}
}//end of main

Output: 12 0 Exception caught 0

Same program can be made in another way, when try block calls a function that contains an
exception.

#include<iostream>
using namespace std;
void fun();
int main()
{
try //try calls a function that contains an exception
{
fun();
}
catch(int x)
{
cout<<"Exception caught "<<x;
}

Amit Mithal, Department of Computer Science and Engineering Page no: 35 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
}
void fun()
{
int a,b;
cin>>a>>b;
if(b!=0)
{
cout<<a/b<<endl;
}
else
throw b;
}

Output: 12 0 Exception caught 0

Multiple Throw and Multiple Catch


There can be situations when throw statement throws multiple types of exceptions, like int
exception, double exception, char exception. In that case, there will be multiple catch blocks to
handle multiple types of exceptions.

WRONG Program showing multiple throw and multiple catch (contains logical error)

#include<iostream>
using namespace std;
void fun(int);
int main()
{
try
{
fun(1);
fun(2);
fun(3);
}
catch(char x)
{
cout<<x<<endl;
}
catch(float x)
{

Amit Mithal, Department of Computer Science and Engineering Page no: 36 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
cout<<x<<endl;
}
catch(int x)
{
cout<<x<<endl;
}
}

void fun(int x)
{
if(x==1)
{
throw 10;
}
if(x==2)
{
throw 'x';
}
if(x==3)
{
throw 3.85;
}

Output of this program will be 10. This program contains a logical error. When 10 is thrown as an
int exception, the matching catch block is executed and other catch blocks are bypassed (just like
switch-case). Then control will NOT return to the try block, as the pair of try-catch block has
finished its work.

Correct Program for multiple throw and multiple catch

#include<iostream>
using namespace std;
void fun(int);
int main()
{
fun(2);
fun(3);
fun(1);
fun(4);

Amit Mithal, Department of Computer Science and Engineering Page no: 37 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
}

void fun(int x)
{
try
{
if(x==1)
{
throw 10;
}
if(x==2)
{
throw 'x';
}
if(x==3)
{
throw 3.85;
}
cout<<"\nEnd of try block.\n";
}
catch(char x)
{
cout<<x<<"\t";
}
catch(double x)
{
cout<<x<<"\t";
}
catch(int x)
{
cout<<x<<"\t";
}
cout<<"\nEnd of try catch system.\n";
}
Output:
x
End of try catch system.
3.85
End of try catch system.
10
End of try catch system.

Amit Mithal, Department of Computer Science and Engineering Page no: 38 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming

End of try block.

End of try catch system.

Multiple Throw and Single Catch (Generic catch)


It is possible to catch multiple types of exceptions (thrown using multiple throw statements) in a
single catch block, using catch(...). So, we can say that when multiple types of exceptions are
thrown, then they are handled using a single catch block, using catch(...). Such type of catch
statement is called as a generic catch.

Example for Multiple Throw and Single Catch (Generic catch)

#include<iostream>
using namespace std;
void fun(int);
int main()
{
fun(2);
fun(3);
fun(1);
fun(4);
}

void fun(int x)
{
try
{
if(x==1)
{
throw 10;
}
if(x==2)
{
throw 'x';
}
if(x==3)
{
throw 3.85;

Amit Mithal, Department of Computer Science and Engineering Page no: 39 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
}
cout<<"\nEnd of try block.\n";
}
catch(...)
{
cout<<”\nCaught an exception";
}
cout<<"\nEnd of try catch system.";
}
Output:
Caught an exception
End of try catch system.
Caught an exception
End of try catch system.
Caught an exception
End of try catch system.

End of try block.

End of try catch system.

Rethrowing an Exception
An exception can be rethrown without processing it first. An exception is rethrown using the
statement throw; without any arguments.

This causes the current exception to be thrown to the next enclosing try-catch sequence and is
caught by a catch statement listed after that enclosing try block. When an exception is rethrown,
it will not be caught by the same catch block or any other catch in that group. Rather, it will be
caught by an appropriate catch in the outer try-catch sequence only.

A catch handler itself may detect and throw an exception. Here again, the exception thrown will
not be caught by any catch statements in that group. It will be passed on to the next outer try-
catch sequence for processing.

Example for rethrowing an exception

#include<iostream>
using namespace std;
void fun(int);

Amit Mithal, Department of Computer Science and Engineering Page no: 40 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
int main()
{
cout<<"Top of main\n";
try
{
fun(16);
}
catch(int x3)
{
cout<<"Exception recaught "<<x3<<endl;
}
cout<<"Bottom of main\n";
}

void fun(int x1)


{
cout<<"Top of fun\n";
try
{
throw x1;
}
catch(int x2)
{
cout<<"Exception caught "<<x1<<endl;
throw;
}
cout<<"Bottom of fun\n"; //this statement will not be read
}

/* Output:
Top of main
Top of fun
Exception caught 16
Exception recaught 16
Bottom of main */

Amit Mithal, Department of Computer Science and Engineering Page no: 41 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
Specifying Exceptions
It is possible to specify only certain types of exceptions that we want to throw, catch and handle
in our program. This is done by specifying those certain exceptions in the function definition. The
general form of an exception specification is:

type function(argument-list) throw (exception-type)

In the above format, the exception type specifies the type of exception that can be thrown by that
function. Throwing any other type of exception will cause abnormal program termination.

This format of specifying exceptions is only applicable for the exceptions that the function throws
back to the try block that called it. This means that this exception specification applies only when
throwing an exception out of the function and NOT within the function.

Example 1 for exception specification - how to restrict a function to throw only certain exceptions
and not all

#include<iostream>
using namespace std;
void fun(int) throw(int);
int main()
{
try
{
fun(1);
fun(2);
}
catch(char x)
{
cout<<x<<endl;
}
catch(int x)
{
cout<<x<<endl;
}
}

Amit Mithal, Department of Computer Science and Engineering Page no: 42 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
void fun(int x) throw(int)
{
if(x==1)
{
throw 'x';
}
else
{
if(x==2)
{
throw 12;
}
}
}

// Output: Terminate called after throwing an instance of 'char'

Example 2 for exception specification - how to restrict a function to throw only certain exceptions
and not all

#include<iostream>
using namespace std;
void fun() throw (int);
int main()
{
try
{
fun();
}
catch(int x)
{
cout<<x<<endl;
}
}

void fun() throw (int)


{
throw 12;
}

// Output: 12

Amit Mithal, Department of Computer Science and Engineering Page no: 43 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming

Example to specify nil exception to be thrown by a function

If we want that a function should not throw any exception, then in the above format of exception
specification, the exception-type should be empty i.e.

type function(argument-list) throw (); // empty exception type inside throw

#include<iostream>
using namespace std;
void fun() throw ();
int main()
{
try
{
fun();
}
catch(int x)
{
cout<<x<<endl;
}
}
void fun() throw ()
{
throw 12;
}

// Output: Terminate called after throwing an instance of 'int'

File Handling
We already know how to perform read operation from keyboard and write operation to the monitor,
using cin and cout respectively. Additionally, read and write operations can also be performed on
files, stored in the hard disk of the computer system. Performing read and write operations in files
is required because many real life problems handle large volumes of data, and which can be done
using files.

Example to perform read and write operation in files

#include<iostream>

Amit Mithal, Department of Computer Science and Engineering Page no: 44 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
#include<fstream>
using namespace std;
int main()
{
ofstream ob1("f2.txt"); //output stream class ofstram. open file f2.txt
int a[5],i;
for(i=0;i<=4;i++)
{
cin>>a[i]; //read from keyboard
ob1<<a[i]<<endl; //write to file f2.txt
}

ob1.close();

ifstream ob2("f2.txt"); //input stream class ifstream


for(i=0;i<=4;i++)
{
ob2>>a[i]; // read from file f2.txt
cout<<a[i]<<endl; // write on monitor
}

ob2.close();
}

QUESTION BANK
1) What is an inline function? Write a program which supports inline function.

2) Identify the situations where an inline expansion may not work. What type of functions should
be made as inline? What precautions are required before making a function as inline? Under what
circumstances the benefits of an inline function may diminish? What are the advantages and
disadvantages of making a function as inline?

3) Compare the properties of constructor and destructor.

4). Explain the two uses of the visibility modes or access specifiers- public, private and
protected. Compare and distinguish between public, private and protected.

5) Distinguish between hierarchical inheritance and hybrid inheritance.

Amit Mithal, Department of Computer Science and Engineering Page no: 45 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
6) Explain the concept of pure virtual function with the help of an example. What precautions
must be taken while accessing and calling a function that is virtual?

7) Under what circumstances do we need to use pure virtual function?

8) Write a program in C++ to add two matrices of size mxn, by overloading the + operator.

9) Write a program in C++ to concatenate two strings using operator overloading.

10) Design an Object Oriented Program to add two complex numbers by overloading the binary
operator +.

11) Can we use a friend function to overload a binary operator? If yes, then justify and explain it
by making a program.

12) Suppose A, B and C are objects of the same class, say abc. Design an Object Oriented
program to perform the following operation by overloading binary operator - using friend function:
A = B - 5; Use the following function signature: friend abc operator - (abc, int);

A Note For Students


Dear students,

This online notes is subject to updation.

Please note that this online notes does NOT cover complete syllabus. For complete coverage of
syllabus, you are advised to refer the prescribed syllabus and refer the following books:

List of Books
Text Book
1) Object Oriented Programming with C++ - E Balagurusamy - TMH

Amit Mithal, Department of Computer Science and Engineering Page no: 46 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming
Reference Books
1) Object Oriented Programming in C++ - Robert Lafore -SAMS Publishing
2) Mastering C++ - K R Venugopal, Rajkumar Buyya - TMH
3) The Complete Reference C++ - Herbert Schildt - TMH
4) The C++ Programming Language - Bjarne Stroustrup (The Creator of C++) - Pearson
Education

CO-WISE WEAK STUDENT ASSIGNMENT


Weak Student in CO1- Assignment
Q1/CO1. Explain the features of Object Oriented Programming.
Q2/CO1. Design an object oriented program to explain how the concept of Data Hiding is
achieved in C++.

Weak Student in CO2- Assignment


Q1/CO2. Explain the concept of function overloading with an example.

Q2/CO2. What is the advantage of friend function? Write a program in C++ for friend function.

Weak Student in CO3- Assignment


Q1/CO3. Draw figures for various types of inheritance and define the types of inheritance.
Q2/CO3. What do you mean by virtual function? Design an object oriented program in C++ to
illustrate the concept of pure virtual function.

Amit Mithal, Department of Computer Science and Engineering Page no: 47 of 48


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Object Oriented Programming

CO-WISE STRONG STUDENT ASSIGNMENT


GATE 2005/CO1: Which of the following are essential features of an object-oriented
programming languages?
1. Abstraction and encapsulation
2. Strictly-typedness
3. Type-safe property coupled with sub-type rule
4. Polymorphism in the presence of inheritance
(A) 1 and 2 only (B) 1 and 4 only (C) 1, 2 and 4 only (D) 1, 3 and 4 only

Amit Mithal, Department of Computer Science and Engineering Page no: 48 of 48

You might also like