Professional Documents
Culture Documents
Object Oriented Programming - Online Notes
Object Oriented Programming - Online Notes
TABLE OF CONTENTS
COURSE OUTCOME 2
Syllabus 3
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 9
To access the global version of a variable 9
UNIT - 2 10
Constructor 10
Properties of Constructor 11
Types of constructor 11
Destructor 12
Properties of Destructor 12
Function Overloading 13
Passing Object as Function Argument 15
Friend Function 17
Inline Function 18
UNIT - 3 20
Inheritance 20
Protected class member 22
Access Specifiers (visibility modes) 23
Ways of inheritance: public, private, protected 23
Pointer to Object 25
Virtual Function 26
UNIT - 4 28
Operator Overloading 28
Overloading Binary Operators Using Friend Function 32
UNIT - 5 33
Template 33
Function Template 33
QUESTION BANK 47
List of Books 47
Text Book 47
Reference Books 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:
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
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.
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
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
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
}
void fun(int l,int b)
Output:
200
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:
● Compile time polymorphism (can be achieved using function overloading and operator
overloading)
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
class abc
{
private:
int x; //member data of class abc is x
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
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
{
cout<<"hello";
}
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)
#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:
We are in inner block
k = 20
m = 30
::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
Example of constructor
class abc
{
private:
int x;
public:
abc() //constructor defined
Output:
10
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 implicit and explicit calling of constructor achieves the same effect, but the difference is
that implicit constructor calling is compact than explicit constructor calling.
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:
10
Destructor called
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
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.
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
We know that in function argument, we can pass variables or constants. Similarly, in function
argument, we can also pass object.
class abc
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>
class fruit
{
private:
int 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.
● Friend function may pass an object as its argument
Example of Friend Function
class abc
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
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:
On the execution of these statements, the values of c and d will be 27 and 64 respectively.
#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
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:
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
Parent A B A
A class
Child C C
B B
class
Single Multiple Hierarchical
inheritance inheritance inheritance
A
A
B
B
C C D
Multilevel
inheritance Hybrid
inheritance
class a
{
protected:
int x; /*protected class member x can be accessed in derived class b*/
};
class b : public a
{
public:
void fun()
{
x=10; /*protected class member x accessed in derived
class b*/
cout<<x;
Output: 10
Let us summarize the above in the form of a table, for a quick glance and better presentation.
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.
Output: a
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:
● 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)
UNIT - 4
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 +.
● Some operators which cannot be overloaded are: sizeof operator, scope resolution
operator ::, conditional operator ?:, member selection operator . (dot)
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();
}
Output:
10 11
class abc
{
private:
int x;
public:
void set(int x1)
{
x=x1;
}
void show()
{
cout<<x<<“\t”;
}
void main()
{
abc ob1,ob2;
Output: 3
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();
Output:
1 2
3 4
4 6
class abc
{
int x;
public:
void set(int x1)
{
x=x1;
}
void show()
{
cout<<x<<“\t”;
}
friend abc operator +(int,abc);
};
void main()
{
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.
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.
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.
#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.
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.
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
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
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();
}
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;
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.
#include<iostream>
using namespace std;
void fun(int);
int main()
{
fun(2);
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
#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)
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.
#include<iostream>
using namespace std;
/* Output:
Top of main
Top of fun
Exception caught 16
Exception recaught 16
Bottom of main */
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.
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;
}
}
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;
}
}
// Output: 12
If we want that a function should not throw any exception, then in the above format of exception
#include<iostream>
using namespace std;
void fun() throw ();
int main()
{
try
{
fun();
}
catch(int x)
{
cout<<x<<endl;
}
}
void fun() throw ()
{
throw 12;
}
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.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ob1.close();
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?
4). Explain the two uses of the visibility modes or access specifiers- public, private and
protected. Compare and distinguish between public, private and protected.
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?
8) Write a program in C++ to add two matrices of size mxn, by overloading the + operator.
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);
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
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
Q2/CO2. What is the advantage of friend function? Write a program in C++ for friend function.