0% found this document useful (0 votes)
3 views

OOPS Notes

The document provides an overview of programming paradigms, detailing imperative, procedural, object-oriented, and declarative programming approaches. It emphasizes the significance of object-oriented programming (OOP) in addressing limitations of procedural programming, highlighting key concepts such as encapsulation, inheritance, polymorphism, and dynamic binding. Additionally, it introduces C++ as an object-oriented programming language, outlining its structure and features.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

OOPS Notes

The document provides an overview of programming paradigms, detailing imperative, procedural, object-oriented, and declarative programming approaches. It emphasizes the significance of object-oriented programming (OOP) in addressing limitations of procedural programming, highlighting key concepts such as encapsulation, inheritance, polymorphism, and dynamic binding. Additionally, it introduces C++ as an object-oriented programming language, outlining its structure and features.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

1/7/24, 4:44 PM OOPS Notes

UNIT I
Introduction of Programming Paradigms
Paradigm can also be termed as method to solve some problem or do some task.
Programming paradigm is an approach to solve problem using some programming language
or also we can say it is a method to solve a problem using tools and techniques that are
available to us following some approach. There are lots for programming language that are
known but all of them need to follow some strategy when they are implemented and this
methodology/strategy is paradigms. Apart from varieties of programming language there are
lots of paradigms to fulfill each and every demand. They are discussed below:
1. Imperative programming paradigm:
It is one of the oldest programming paradigm. It features close relation to machine
architecture. It is based on Von Neumann architecture. It works by changing the program
state through assignment statements. It performs step by step task by changing state. The
main focus is on how to achieve the goal. The paradigm consist of several statements and
after execution of all the result is stored.
Advantage:
 Very simple to implement
 It contains loops, variables etc.
Disadvantage:
 Complex problem cannot be solved
 Less efficient and less productive
 Parallel programming is not possible
Examples of Imperative programming paradigm:
C : developed by Dennis Ritchie and Ken Thompson
Fortran : developed by John Backus for IBM
Basic : developed by John G Kemeny and Thomas E Kurtz
Imperative programming is divided into three broad categories: Procedural, OOP and parallel
processing. These paradigms are as follows:
 Procedural programming paradigm –
This paradigm emphasizes on procedure in terms of under lying machine model. There is no
difference in between procedural and imperative approach. It has the ability to reuse the code
and it was boon at that time when it was in use because of its reusability.
Examples of Procedural programming paradigm:

about:blank 1/90
1/7/24, 4:44 PM OOPS Notes

C : developed by Dennis Ritchie and Ken Thompson


C++ : developed by Bjarne Stroustrup
Java : developed by James Gosling at Sun Microsystems
ColdFusion : developed by J J Allaire
Pascal : developed by Niklaus Wirth

 Object oriented programming –


The program is written as a collection of classes and object which are meant for
communication. The smallest and basic entity is object and all kind of computation is
performed on the objects only. More emphasis is on data rather procedure. It can handle
almost all kind of real life problems which are today in scenario.
Advantages:
 Data security
 Inheritance
 Code reusability
 Flexible and abstraction is also present
Examples of Object Oriented programming paradigm:
Simula : first OOP language
Java : developed by James Gosling at Sun Microsystems
C++ : developed by Bjarne Stroustrup
Objective-C : designed by Brad Cox
Visual Basic .NET : developed by Microsoft
Python : developed by Guido van Rossum
Ruby : developed by Yukihiro Matsumoto
Smalltalk : developed by Alan Kay, Dan Ingalls, Adele Goldberg
2. Declarative programming paradigm:
It is divided as Logic, Functional, Database. In computer science the declarative
programming is a style of building programs that expresses logic of computation without
talking about its control flow. It often considers programs as theories of some logic. It may
simplify writing parallel programs. The focus is on what needs to be done rather how it
should be done basically emphasize on what code is actually doing. It just declares the result
we want rather how it has be produced. This is the only difference between imperative (how
to do) and declarative (what to do) programming paradigms. Getting into deeper we would
see logic, functional and database.
2

about:blank 2/90
1/7/24, 4:44 PM OOPS Notes

 Logic programming paradigms –


It can be termed as abstract model of computation. It would solve logical problems like
puzzles, series etc. In logic programming we have a knowledge base which we know before
and along with the question and knowledge base which is given to machine, it produces
result. In normal programming languages, such concept of knowledge base is not available
but while using the concept of artificial intelligence, machine learning we have some models
like Perception model which is using the same mechanism.
In logical programming the main emphasize is on knowledge base and the problem. The
execution of the program is very much like proof of mathematical statement, e.g., Prolog
 Functional programming paradigms –
The functional programming paradigms has its roots in mathematics and it is language
independent. The key principle of this paradigms is the execution of series of mathematical
functions. The central model for the abstraction is the function which are meant for some
specific computation and not the data structure. Data are loosely coupled to functions. The
function hide their implementation. Function can be replaced with their values without
changing the meaning of the program. Some of the languages like perl, javascript mostly uses
this paradigm.
Examples of Functional programming paradigm:
JavaScript : developed by Brendan Eich
Haskell : developed by Lennart Augustsson, Dave Barton
Scala : developed by Martin Odersky
Erlang : developed by Joe Armstrong, Robert Virding
Lisp : developed by John Mccarthy
ML : developed by Robin Milner
Clojure : developed by Rich Hickey
The next kind of approach is of Database.
 Database/Data driven programming approach –
This programming methodology is based on data and its movement. Program statements are
defined by data rather than hard-coding a series of steps. A database program is the heart of a
business information system and provides file creation, data entry, update, query and
reporting functions. There are several programming languages that are developed mostly for
database application. For example SQL. It is applied to streams of structured data, for

about:blank 3/90
1/7/24, 4:44 PM OOPS Notes

filtering, transforming, aggregating (such as computing statistics), or calling other programs.


So it has its own wide application.

about:blank 4/90
1/7/24, 4:44 PM OOPS Notes

UNIT II
Object Oriented Programming (OOP)
The major motivating factor in the invention of object-oriented approach is to remove
some of the drawbacks encountered in the procedural approach. OOP treats data as a critical
element in the program developments and does not allow it to flow freely around the system.
It ties data more closely to the functions that operate on it, and protects it from accidental
modification from outside functions. OOP allows decomposition of a problem into a number
of entities called objects and then builds data and functions around these objects. the
organization of data and functions in OOP is shown in following figure.
Object A object B

Data
Data Data

Function
Function

Object C

Function

Data

The data of an object can be accessed only by the functions associated with that object,
however functions of one object can access the functions of another object.
Some of the features of OOP are
 Emphasis is on data rather than procedure.
 Programs are divided into what are known as objects.
 Functions that operate on the data of an object are tied together in the data structure
 Data is hidden and cannot be accessed by external functions.
 Objects may communicate with each other through functions
 New data and functions can be easily added whenever necessary

about:blank 5/90
1/7/24, 4:44 PM OOPS Notes

We define object oriented programming as an approach that provides a way of


modularizing programs by creating partitioned memory are for both data and functions
that can be used as templates for creating copies of such modules on demand.
Basic concepts of OOP
1 objects
2 classes
3 data abstraction and encapsulation
4 inheritance
5 polymorphism
6 dynamic binding
7 message passing
Objects
Objects are the basic run time entities in object oriented system. They may represent a
person, a place, a bank account or any item that the program has to handle. Objects takes
up space in the memory and have an associated address in memory. Each object contain
data and code to manipulate the data . following fig shows notation that is used in object-
oriented analysis to represent an object.

Object:student
Input()
DATA
Rno , name,
marks Display()

Functions
Input() Percent()
Display()
Percent()

Classes
The entire set of data and code of an object can be made a user-defined data type with
the help of a class. In fact, objects are variables of type class. Once a class has been
defined, we can create any number of objects belonging to that class. Each object is
associated with the data of type class with which they are created. A class is thus a
collection of objects of similar type. For example, mango, orange, apple are objects of
type class fruit. Classes are user defined data type and behave like the built-in types. The
syntax used to create object is no different than the syntax used to create an integer in C.
6

about:blank 6/90
1/7/24, 4:44 PM OOPS Notes

Data abstraction and encapsulation


The wrapping up of data and functions into a single unit (called class) is known as
encapsulation. It is the striking feature of a class. The data is not accessible to the outside
world , and only those functions which are wrapped in the class can access it. These
functions provide the interface between the object’s data and the program. This insulation
of data from direct access by the program is called data hiding.
Abstraction refers to the act of representing essential features without including the
background details. Classes use the concept of abstraction and are defined as the list of
abstract attributes, and functions to operate on these attributes. The attributes are called as
data members. And the functions are called as member functions. Since the classes use
the concept of data abstraction, they are known as abstract data types(ADT).

Inheritance
Inheritance is a process by which objects of one class acquire the properties of objects of
another class. In OOP , the concept of inheritance provides the idea of reusability. This
means that we can add additional features to an existing class without modifying it. This
is possible by deriving a new class from existing one. The new class will have the
combined features of both the classes. The power of mechanism of inheritance is that it
allows the programmer to reuse a class that is almost, but not exactly what he wants.

Polymorphism
Polymorphism, a greek term, means the ability to take more than one form. An operation
may exhibit different behaviors in different instances. Behavior depends upon the types of
data use din the operation. For example, consider the opearation of addition. For two
numbers , the operation will generate sum . if the operands are two strings, then the
operation would produce a third string by concatenation. The process of making an
operator to exhibit different behaviors in different instances is known as operator
overloading.
Similarly single function name can be used to handle different number and types of
arguments. This is something similar to a particular word having different meanings
depending on the context. Using a single function name to perform different types of
tasks is known as function overloading.

about:blank 7/90
1/7/24, 4:44 PM OOPS Notes

Dynamic binding
Binding refers to the linking of a procedure call to the code to be executed in
response to the call. Dynamic binding means that the code associated with a given
procedure call is not known until the time of call at run time.
Message passing
An object oriented program consists of a set of objects that communicate with each other.
The process of programming in an object oriented language , therefore involves the
following steps.
1 creating classes that define objects
2 creating objects from class definition
3 establishing communication among objects
objects communicate with one another by sending and receiving information much the same
way as people pass messages to one another. A message for an object is a request for
execution of a procedure, and therefore will invoke a function in the receiving object that
generates the desired result. Message passing involves specifying the name of the object , the
name of the function, and the information to be sent. For example
emp1.salary(name);

object information
message
Benefits of OOP
1 Through inheritance, we can eliminate redundant code and extend the use of
existing class
2 We can build programs from the standard working modules that communicate
with one another rather than having to start from scratch. This leads to saving of
development time and higher productivity.
3 The principle of data hiding helps programmer to build secure programs.
4 Object oriented systems can be easily upgraded from small to large systems.
5 It is possible to have multiple instances of an object to co-exist without any
interference.

Introduction to C++

about:blank 8/90
1/7/24, 4:44 PM OOPS Notes

C++ is an object oriented programming language. It was developed by Bjarne


Stroustrup at AT&T Bell laboratories in 1980. Stroustrup, an admirer of Simula67 and
strong supporter of C , wanted to combine the best of both the languages and create a
more powerful language that could support object-oriented programming features and still
retain the power and elegance of C, the result was C++. Therefore C++ is an extension to
C with a class construct feature of simula67. C++ is a superset of C. therefore all C
programs are also C++ programs.
Structure of C++ program
A typical c++ program would contain four sections as follows. These files may be placed
in separate code files and then compiled independently or jointly

Include files section


Class declaration
Member function definition
main() program

it is common practice to organize a program into three separate files. The class
declaration are placed in a header file and definitions of member functions go into another
file. This approach enables programmer to separate the abstract specification of the
interface(class declaration) from the implementation details(member function definition).
Finally the main program that uses the class is placed in a third file which includes the
other two files.

Comments
C++ introduces a new comment symbol // . comments start with a double slash symbol
and terminate at the end of the line. A comment may start anywhere in the line, and
whatever follows till the end of the line is ignored. // symbol is a single line comment. C
comment symbols /* and */ are still valid in C++ and are more suitable for multiple line
comment. We can use either or both symbols in our program.
e.g
// this program is to illustrate
// the use of function overloading
or
/* this program is to illustrate
9

about:blank 9/90
1/7/24, 4:44 PM OOPS Notes

the use of function overloading*/

output operator
The statement
cout<<”C++ is a superset of C”;
causes the string in quotation marks to be displayed on the screen. This statement
introduces two new C++ features, cout and <<. cout is a predefined object that represents
the standard output stream in C++. Here the standad output stream is screen. The operator
<< is called insertion or put to operator. It inserts the contents of a variable in its right to
the object on its left.
e.g cout<<x;
display value of x on the screen.
This operator can be cascaded as follows
cout<<”Sum=”<<s<<”Average=”<<a;
above statement first sends the string “sum=” then sends the value of s then sends string
“Average=” and then value of a so that output will be like
sum=12 Average=6

Input operator
The statement
cin>>num1;
is an input statement and causes the program to wait for the user to type in a number. The
number keyed in is placed in variable num1. The identifier cin is a predefined object in
C++ that corresponds to the standard input stream. Here this stream represents the
keyboard. The opearator >> is called extraction or get from operator. It extracts the value
from the keyboard and assigns it to variable on its right. This operator can be overloaded
as follows.
cin>>num1>>num2;
User Defined functions

If a program is divided into functional parts, then each part may be independently
coded and later combined into a single unit. The independently coded programs are called as
subprograms that are much easier to understand , debug and test, such subprograms are called
as functions.

10

about:blank 10/90
1/7/24, 4:44 PM OOPS Notes

There are times when certain types of operations or calculations are repeated at many
points throughout a program. For instance, we might use factorial of a number at several
points in a program. In such situations, we may repeat the program statements wherever they
are needed. Another approach is to design a function that can be called and used whenever
required. This saves both time and space. This approach clearly results in number of
advantages.
1. It facilitates top-down modular programming . in this programming style, the high
level logic is solved first while the details of each lower level function are addressed
later.
2. The length of a source program can be reduced by using functions at appropriate
places.
3. It is easy to locate and isolate a faulty function for further investigations.
4. A function may be used by other programs. This means that a C++ programmer can
build on what others have already done, instead of starting all over again from scratch.
Elements of user defined functions

In order to make use of a user defined functions, we need to establish three elements
that are related to functions.
1. Function Declaration or function prototype
2. Function Definition
3. Function Call
Function declaration or function prototype

Like variables, all functions in a C++ program must be declared, before they are used
in the program. Format of function declaration is
Return-type function-name(parameter list);
Where return-type is the data type of value which is returned from the function. Function-
name is the name of the function which can be anything just like variables. Parameter list is
the list of parameter required for the function. They should be separated by comma. E.g.
function for multiplication of two integers can be declared as
int mul(int m,int n);
equally acceptable forms of mul() are
int mul(int,int);
mul(int a,int b);
mul(int,int);

11

about:blank 11/90
1/7/24, 4:44 PM OOPS Notes

When return-type is not specified then by default function returns an integer value. When
a function does not return a value and doesn’t take any arguments it can be declared as
void display(void);
Definition of funcion

A function definition , also known as function implementation includes the following


elements
1. Function name
2. function return-type
3. list of parameters
4. local variable declaration
5. function statements
6. a return statement
All the six elements are grouped into two parts
 Function header (First three elements)
 Function Body (Last three elements)
A general format of function definition is

Return-type function-name(parameter list)


{
local variable declaration
statement-1
statement-2
------
------
return (expression)
}
The first line is known as function header. And the statements within { and }
constitute function body. In above format
return-type specifies the type of value that the function is expected to return to the
calling function. If the return-type is not specified , C++ will assume that it is an integer type.
If the function is not returning anything then we need to specify the return type as void.
The function-name is any valid identifier and therefore follow the same rules as
variables.

12

about:blank 12/90
1/7/24, 4:44 PM OOPS Notes

The parameter list declares the variables that will receive the data sent by the calling
program. They serve as input data to the function to carry out the specific task. They are
referred as formal parameters. The parameters are also known as arguments. The parameter
list contains declaration of variables separated by commas. A function need not always
receive values from the calling program. In such cases functions have no formal parameters.
To indicate that the parameter list is empty, we use the keyword void as follows
void display(void)
{
--------
--------
}
this function neither receives any input nor return any value from the function.
Function Body

The function body contains the declarations and statements necessary for performing the
required task. The body enclosed in braces three parts.
1. local variable declaration
2. function statements
3. return statement
if a function does not return any value , we can omit the return statement.
Some examples of function definition are
1) float mul(float a,float b)
{
float c;
c=a*b;
return c;
}
2) void add(int a,int b)
{
Cout<<a+b;
}

3) void display()
{

13

about:blank 13/90
1/7/24, 4:44 PM OOPS Notes

Cout<<“***”;
}
FUNCTION CALL

A function can be called by simply using the function name followed by a list of
actual arguments, if any enclosed in parentheses. E.g mul() can be called as follows
mul(12,10);
when the compiler encounters a function call, the control is transferred to the function mal().
This function is then executed line by line as described and a value is returned when a return
statement is encountered.
The format of a program containing a user defined function is as follows
main()
{
int mul(int,int); /* Function Declaration*/ Calling
y=mul(12,3); /* Function Call */ function
cout<<y;
}
int mul(int a,int b)
{
int m; /* local variable declaration*/ Called function
m=a*b;
return(m); Function Definition
}
While calling program actual parameters are copied into formal parameters i.e. in
above program 12 and 3 will be copied into a and b respectively. Then after executing return
statement, control is transferred back to the calling function from where it is called i.e. in
above program 36 will be returned to the main() and store it in y.

Inline functions
One of the objectives of a function is to save some memory, which becomes
appreciable when a function is likely to be called many times. However , every time a
function is called, it takes a lot of extra time in executing a series of instruction for tasks
such as jumping to function, saving registers, pushing arguments into stack, and returning
to calling function. When a function is small, a lot of time will be spent in such

14

about:blank 14/90
1/7/24, 4:44 PM OOPS Notes

overheads. To eliminate the cost of calls to small functions, C++ proposes a new feature
called 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. The inline functions are defined as follows

inline function-header
{
function body
}
example,
inline float area(int r)
{
return(3.14*r*r);
}
the above function can be called as
A=area(4);
Usually , the function are made inline when they ae small enough to be defined in one or
two lines. 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.
Some of the situations where inline functions may not work are
1 for functions returning values, if a loop, a switch, or goto exists.
2 For functions not returning values, if a return statement exists.
3 If functions contain static variables.
4 If function is recursive.
Example
inline float area(int r)
{
return(3.14*r*r);
}
main()
{
float A;
A=area(5);
15

about:blank 15/90
1/7/24, 4:44 PM OOPS Notes

cout<<”Area=”<<A;
}

Default arguments
C++ allows us to call a function without specifying all its arguments. In such case , the
function assigns a default value to the parameter which does not have a matching argument in
the function call. Default values are specified when the function is declared. The compiler
looks at the prototype to see how many arguments a function uses and alerts the program for
possible default values. Here is an example of a prototype with default values.
float interest(float p , float n , float r=2.5);
the default value is specified in a manner similar to a variable initialization. The above
prototype declares a default value of 2.5 to the argument r. A function call like
x=interest(2000,3);
passes the value of 2000 to p and 3 to n and lets the function use default value of 2.5 for r.
The call
x=interest(2000,3,2);
passes an explicit value of 3 to r.
One important point to note is that only the trailing arguments can have default values and
therefore we must add defaults from right to left. Some examples of function declaration
with default arguments are
int add(int a,int b=30,int c=20); //legal
int add(int a=10,int b,int c); //illegal
int add(int a=10,int b,int c=20); //illegal
int add(int a=10,int b=30,int c=20); //legal
Example
#include<iostream.h>
void main()
{
void print(char c=”*”,int n=20);
print();
cout<<”C++ is superset of C\n”;
print(“@”);
print(“-“,50);
}
16

about:blank 16/90
1/7/24, 4:44 PM OOPS Notes

void print(char c , int n)


{
for(int I=1;I<=n;I++)
cout<<c;
}
O/P of the above program would be
*******************
C++ is superset of C
@@@@@@@@@@@@@@@@@@@
-------------------

Function Overloading

Overloading refers to the use of same thing for different purposees. C++ also permits
overloading of functions. This means that we can use the same function name to create
functions that perform different operations. This is known as function polymorphism in OOP.
Using the concept of function overloading, we can design the family of functions with
one function name but with different argument lists. The function would perform different
operations depending on the argument lists in the function call. The correct function to be
invoked is determined by checking the number and type of arguments but not on the function
type. For example, an overloaded add( ) handles different types of data as shown below.
Declarations
int add(int a, int b);
int add(int a, int b, int c);
double add(int a, double b);
double add(double a, double b);
double add(double a, int b);
Function calls
cout<<add(24,56);
cout<<add(24,56,78);
cout<<add(24,56.23);
cout<<add(24.25,56.25);
cout<<add(24.50,56);

17

about:blank 17/90
1/7/24, 4:44 PM OOPS Notes

a function call first matches the prototype having the same number and type of
arguments and then calls the appropriate function for execution. A best match must be unique.
If an exact match is not found , the compiler uses the integral promotions to the actual
arguments, such as
char to int
float to double
to find a match.
Example
int volume(int s)
{
return(s*S*S);
}

float volume(float r ,float h)


{
return(3.14*r*h);
}

float volume(float l ,float b ,float h)


{
return( l * b * h);
}

void main()
{
cout<<”Volume of cube=”<<volume(4);
cout<<”Volume of cylinder=”<<volume(4.5,5);
cout<<”Volume of rectangular box=”<<volume(4 ,3 ,6);
}

18

about:blank 18/90
1/7/24, 4:44 PM OOPS Notes

Classes and Objects


Specifying a class
A class is an extension of the idea of structure used in C. it is a new way of creating
and implementing a user-defined data type. It is a way to bind the data and its associated
functions together. It allows the data to be hidden, if necessary, from external use. When
defining a class, we are creating a new extract data type that can be treated like any other
built-in data type.
A class specification has two parts
1 Class declaration
2 Class function definition
The class declaration describes the type and scope of its members. The class function
definition describes the how the class functions are implemented.
The general form of class declaration is
class class_name
{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};

the keyword class specifies that what follows is an abstract data type of type
class_name. The body of a class is enclosed within braces and terminated by semicolon.
The class body contains the declaration of variables and functions. These variables and
functions are collectively called class members. They are usually grouped under two
sections, namely private and public to denote which of the members are public and which
of them are private. The keyword public and private are called visibility labels or access
modifiers.
The class members that have been declared as private can be accessed only from witin
the class. On the other hand, public members can be accesd from outside the class also.

19

about:blank 19/90
1/7/24, 4:44 PM OOPS Notes

The data hiding is a key feature of object oriented programming. The keyword private is
optional. By default, the members of a class are private.
The variables declared in a class are known as data members and functions are known
as member functions. Only the member functions can have access to the private data
members and private functions. However , the public members can be accessed from
outside of the class.
For example
class student
{
private:
int rno;
char *name;
public:
void getdata();
void putdata();
};
In above example, student is a class name which can be used to create instances of that
class type. It contains two private data members(rno and *name) and two public member
functions. getdata() is used assign values to rno and name. putdata() is used to display the
values of rno and name. here only member functions have access to rno and name. no
other functions can access these values.
Creating objects
Remember that the class declaration does not define any object , but only specifies what
they will contain. Once a class has been declared , we can create variables of that type by
using the class name (like any other built-in type).
For example
student s1;
creates a variable s1 of type student. In C++ class variables are known as
objects.therefore s1 is called object of class student. We may also declare number of
objects in one statement as follows:
student s1,s2,s3;
objects can be created when a class is defined by placing their names immediately after
the closing brace as follows.

20

about:blank 20/90
1/7/24, 4:44 PM OOPS Notes

class student
{
private:
int rno;
char *name;
public:
void getdata(int , char *);
void putdata();
}s1,s2,s3;

Accessing Class Members


The private data of a class can be accessed only through member functions of that class.
The following is the format for calling a member function.
Object-name.function-name(actual-arguments);
e.g the function call statement
x.getdata(100,”Rahul”);
calls getdata() and passess the values 100 and “Rahul” to the data members of the object
x.
similarly the statement
x.putdata();
displays the data members of the object x. A member function must be accessed through
the object name only i.e. the statement such as
putdata();
has no menaing. Similarly the statement
x.number=10; is invalid if the data member number is private. The number can be
accessed only by the member functions and not by the object of the class.
A variable declared as public can be accessed by the object directly. Example:
class xyz
{
int x;
int y;

21

about:blank 21/90
1/7/24, 4:44 PM OOPS Notes

public:
int z;
};
---------
---------
xyz x1;
x1.x=10; //invalid
x1.z=13; //valid
---------
---------

Defining Member Functions


Member functions can be defined in two ways
 Outside the class definition
 Inside the class definition
Outside the class definition
Member functions declared inside the class have to defined seperately outside the class. Their
definitions are very much similar to normal functions. They should have a function header
and function body. An important difference between a member function and a normal
function is that a member function incorporates a membership identity label in the header.
This label tells the compiler which class the function belongs to. The general form of a
member function definition outside the class is:
Return-type class-name : : function-name(argument declaration)
{
function body
}
The membership label : : tells the compiler that function function-name belongs to class
class-name. The symbol : : is called as scope resolution operator.
e.g.
void student::getdata( int no , char *na)
{
rno=no;
strcpy(name, na);

22

about:blank 22/90
1/7/24, 4:44 PM OOPS Notes

}
void student::putdata( )
{
cout<<”Roll no:”<<rno;
cout<<”Name:”<<name;
}

Inside the class definition


Another method of class definition is to replace the function declaration with actual
function definition inside the class. For example,
Class student
{
int rno;
char *name;
public:
void getdata( int no , char *na)
{
rno=no;
strcpy(name, na);
}
void putdata( )
{
cout<<”Roll no:”<<rno;
cout<<”Name:”<<name;
}
};
when a function is defined inside a class , it is treated as an inline function. Therefore the
restrictions and limitations applied to an inline function are also applicable here. Normally,
only small function are defined in the class.
C++ program with a class
#include<iostream.h>
class circle
{

23

about:blank 23/90
1/7/24, 4:44 PM OOPS Notes

int r;
float a,p;
public:
void getdata(int rad)
{
r =rad;
a=3.14*r*r;
p=2 * 3.14 *r;
}
void putdata( )
{
cout<<”Area=”<<a<<”\n”;
cout<<”Circumference=”<<p;
}
};
void main()
{
circle c1;
c1.getdata(4);
c1.putdata();
}

Making an outside function inline


It is a good practice to define the member functions outside the class. We can define
the member function outside and still make it inline by using the qualifier inline as follows
inline void student :: putdata()
{
cout<<”rno=”<<rno<<”\n”;
cout<<”Name :”<<name;
}

Nesting of member functions

24

about:blank 24/90
1/7/24, 4:44 PM OOPS Notes

A member function of a class can called by its name inside another member function of the
same class. This is known as nesting of member functions.
#include<iostream.h>
class circle
{
int r;
float a,p;
public:
void getdata();
void calculateap();
void putdata();
};
void circle::getdata(int rad)
{
r =rad;
calculateap();
}
void circle::putdata( )
{
cout<<”Area=”<<a<<”\n”;
cout<<”Circumference=”<<p;
}
void circle::calculateap()
{
a=3.14*r*r;
p=2*3.14*r;
}
void main()
{
circle c1;
c1.getdata(4);
c1.putdata();
}

25

about:blank 25/90
1/7/24, 4:44 PM OOPS Notes

Private member functions


Although it is normal practice to place all the data items in a private section and all the
functions in a public, some situations may require certain functions to be hidden from the
outside calls.
Tasks such as deleting an account in a customer file, or providing increment to employee are
events of serious consequences and therefore the functions handling such tasks should have
restricted access. We can place these functions in the private sections.
A private member function can be called by another member function of a class.
Consider the following example.
#include<iostream.h>
class circle
{
int r;
float a,p;
void calculateap();
public:
void getdata();
void putdata();
};
void circle::getdata(int rad)
{
r =rad;
calculateap();
}
void circle::putdata( )
{
cout<<”Area=”<<a<<”\n”;
cout<<”Circumference=”<<p;
}
void circle::calculateap()
{
a=3.14*r*r;
p=2*3.14*r;

26

about:blank 26/90
1/7/24, 4:44 PM OOPS Notes

}
void main()
{
circle c1;
c1.getdata(4);
c1.putdata();
}
OBJECTS AS FUNCTION ARGUMENTS
Like any other data type, an object may be used as function arguments. This can be done in
two ways:
 A copy of the entire object is passed to the function (pass by value)
 Only the reference of the object is transferred to the function (pass by reference)
In call by value, since a copy of the object is passed to the function, any changes made to the
object inside the function does not affect the object used to call the function. Whereas in call
by reference, the function works directly on the actual object used in the call. This means that
any changes made to the object inside the function will reflect in the actual object.
Program
#include<iostream.h>
class complex
{
int x,y;
public:
void getdata(int a,int b)
{
x=a;
y=b;
}
void display()
{
cout<<x<<”+”<<y<<”i”<<endl;
}
void add(complex c1,complex c2)
{
x=c1.x+c2.x;
27

about:blank 27/90
1/7/24, 4:44 PM OOPS Notes

y=c1.y+c2.y;
}
};
void main()
{
complex A ,B,C;
A.getdata(2,3);
B.getdata(1,7);
C.add(A,B);
Cout<<”Addition=”;
C.display();
}
FRIEND FUNCTION
we know that the private members can’t be accessed from outside the class. That is,
non member function can’t have access to the private data of a class. However , there could
be situation, where we would like two classes to share a particular function. For example,
consider a case where two classes, manager and scientist , have been defined. We would like
to use a function income_tax() to operate on the objects of both these classes. In such
situations, C++ allows the common function to be made friendly with both the classes,
thereby allowing the function to have access to the private data of the classes. Such a function
need not be a member of any of these classes.
To make an outside function friendly to a class, we have to simply declare this
function as a friend of the class as follows.
class simple
{
……………
……………
public:
……………
friend void fun1(simple);
};
The function declaration should be preceded by the keyword friend. The function is defined
elsewhere in the program like a normal C++ function.
A friend function possesses certain special characteristics
28

about:blank 28/90
1/7/24, 4:44 PM OOPS Notes

 It is not in the scope of the class


 It can’t be called using the object of the class. It can be invoked like a normal
function.
 Unlike member function , it can’t access the member names directly and has to use an
object name and dot operator with each member name.(A.x)
 It can be declared either as public or private part of a class without affecting its
meaning.
 Usually, it has the objects as function arguments.
Program
class ABC
{
int a,b;
public:
void setdata(int x,int y)
{
a=x;
b=y;
}
friend int add(ABC);
};
int add(ABC A)
{
return(A.a+A.b);
}
void main()
{
ABC A1;
A1.setdata(10,20);
cout<<”Addition=”<<Add(A1);
}

RETURNING OBJECTS
Object can be returned from a function as follows. Following program returns a complex
object from a function.
29

about:blank 29/90
1/7/24, 4:44 PM OOPS Notes

Program
#include<iostream.h>
class complex
{
int x,y;
public:
void getdata(int a,int b)
{
x=a;
y=b;
}
void display()
{
cout<<x<<”+”<<y<<”i”<<endl;
}
friend complex add(complex c1,complex c2);
};
complex add(complex c1,complex c2)
{
complex c3;
c3.x=c1.x+c2.x;
c3.y=c1.y+c2.y;
return c3;
}

void main()
{
complex A ,B,C;
A.getdata(2,3);
B.getdata(1,7);
C=add(A,B);
Cout<<”Addition=”;
C.display();
}
30

about:blank 30/90
1/7/24, 4:44 PM OOPS Notes

CONSTRUCTORS
A constructor is a special member function whose task is to initialize the objects of its class.
It is special because its name is same as class name. the constructor is invoked whenever an
object of its associated class is created. It is called constructor because it construct the values
of data members of the class.
A constructor is declared and defined as follows.
class simple
{
int m , n;
public:
simple( ); //constructor declaration
……………………..
……………………..
};
simple : : simple() //constructor defined
{
m=0; n=0;
}
When a class contains a constructor like the one defined above, it is guaranteed that an object
created by the class will be initialized automatically. For example, the declaration,
simple s1;
not only creates the object s1 of type simple but also initializes its data members m and n to
zero. There is no need to write any statement to invoke the constructor function. A
constructor that accepts no parameters is called default constructors. Default constructor for
class A is A : : A( ). If no such constructor is defined, then the compiler supplies a default
constructor. Therefore statement such as
A a;
invokes the default constructor of the compiler to create the object a.
the constructor function have some special characteristics.
 They should be declared in public section.
 They are invoked automatically when the objects are created.
 They don’t have return types, not even void and therefore they can’t return values.
 They can’t be inherited, though a derived class can call the base class constructor.
31

about:blank 31/90
1/7/24, 4:44 PM OOPS Notes

 Like other C++ functions , they can have default arguments.


 Constructors can’t be virtual.
 We can’t refer to their addresses.
 They make implicit calls to the operators new and delete when memory allocation is
required.
Program for simple constructor
class simple
{
int m , n;
public:
simple( ); //constructor declaration
void display();
};
simple : : simple() //constructor defined
{
m=0; n=0;
}
void simple : : display()
{
cout<<”m=”<<m<<” n=”<<n;
}
void main()
{
simple s;
s.display();
}
OUTPUT
m=0 n=0

PARAMETERIZED CONSTRUCTOR
The constructor simple (), defined above, initializes the data members of all the objects to
zero. However, in practice it may be necessary to initialize the various data elements of
different objects with different values when they are created. C++ permits us to achieve this

32

about:blank 32/90
1/7/24, 4:44 PM OOPS Notes

objective by passing arguments to the constructor function when objects are created. The
constructors that can take arguments are called parameterized constructor.
The constructor simple may be modified to take arguments as shown below.
class simple
{
int m , n;
public:
simple(int x, int y ); //parameterized constructor declaration
……………………..
……………………..
};
simple : : simple(int x,int y) //constructor defined
{
m=x; n=y;
}
When a constructor has been parameterized, the object declaration statement such as
simple s1;
may not work. We must pass the initial values as arguments to the constructor function when
an object is declared. They can be done in two ways:
 By calling constructor explicitly as follows
simple s1=simple(10,20);
 By calling constructor implicitly as follows
simple s1(10,20);
Program for parameterized constructor
class simple
{
int m , n;
public:
simple(int x, int y ); //constructor declaration
void display();
};
simple : : simple(int x , int y) //constructor defined
{
m=x; n=y;
33

about:blank 33/90
1/7/24, 4:44 PM OOPS Notes

}
void simple : : display()
{
cout<<”m=”<<m<<” n=”<<n<<endl;
}
void main()
{
simple s1=simple(10,20); //explicit call
cout<<”Object 1\n”;
s1.display();
simple s2(100,200); //implicit call
cout<<”Object 2\n”;
s2.display();
}
OUTPUT
Object 1
m=10 n=20
Object 2
m=100 n=200

OVERLOADED CONSTRUCTOR
C++ permits us to use more than one constructor in a same class as follows
class simple
{
int m,n;
public:
simple() //default constructor
{
m=0; n=0;
}
simple(int x,int y) //parameterized constructor
{
m=x; n=y;
}
34

about:blank 34/90
1/7/24, 4:44 PM OOPS Notes

…………………………………
…………………………………
};

This declares two constructos for simple object. The first constructor receives no argument.
The second receive two arguments. Therefore the declaration
simple s1;
would automatically invoke the first constructor and set both m and n to 0. The statement
simple s2(10,20);
would automatically invoke the second constructor and set m and n to 10 and 20
respectively.
Such constructor, with more than one definition is called overloaded constructor.
Program for overloaded constructor
class simple
{
int m , n;
public:
simple()
{
m=0; n=0;
}
simple(int x , int y)
{
m=x; n=y;
}
void display();
};
void simple : : display()
{
cout<<”m=”<<m<<” n=”<<n<<endl;
}
void main()
{
simple s1;
35

about:blank 35/90
1/7/24, 4:44 PM OOPS Notes

cout<<”Object 1\n”;
s1.display();
simple s2(10,20);
cout<<”Object 2\n”;
s2.display();
}
OUTPUT
Object 1
m=0 n=0
Object 2
m=10 n=20

CONSTRUCTORS WITH DEFAULT ARGUMENTS


It is possible to define constructors with default arguments. For example the constructor
complex can be declared as follows.
complex(float real , float imag=0);
the default value of the argument imag is 0. Then the statement
complex c1(5.0);
assigns the value 5.0 to real and 0.0 to imag(by default). However the statement,
complex c2(2.0,4.0);
assigns the value 2.0 to real and 4.0 to imag. The actual parameter, when specified , overrides
the default value. Missing arguments must be trailing ones.
PROGRAM FOR CONSTRUCTORS WITH DEFAULT ARGUMENTS
class complex
{
int m,n;
public:
complex(int x , int y=0)
{
m=x; n=y;
}
void display();
};
36

about:blank 36/90
1/7/24, 4:44 PM OOPS Notes

void simple : : display()


{
cout<<m<<”+i”<< n<<endl;
}
void main()
{
Complex s1(10);
cout<<”Object 1\n”;
s1.display();
complex s2(30,20);
cout<<”Object 2\n”;
s2.display();
}
OUTPUT
Object 1
10+i0
Object 2
30+i20

COPY CONSTRUCTOR
A copy constructor is used to declare an initialize an object from another object. For example,
the statement
complex c2(c1);
would define the object c2 and at the same time initialize it to the values of c1. Another form
of this statement is
complex c2=c1;
the process of initializing through a copy constructor is known as copy initialization.
A copy constructor takes a reference to an object of the same class as itself as an argument.
EXAMPLE
class complex
{
int x , y;
public:
complex(int m , int n)
37

about:blank 37/90
1/7/24, 4:44 PM OOPS Notes

{
x=m ; y=n;
}
complex( complex & c)
{
x=c.x ;
y=c.y;
}
void display();
};
void simple : : display()
{
cout<<x<<”+i”<< y<<endl;
}
void main()
{
complex s1(10,20);
cout<<”Object 1\n”;
s1.display();
complex s2(s1);
cout<<”Object 2\n”;
s2.display();
}
OUTPUT
Object 1
10+i20
Object 2
10+i20

DESTRUCTORS
A destructor as the name implies, is used to destroy the objects that have been created
by a constructor. Like a constructor , the destructor is a member function whose name is same
as class name but is preceded by tilde(~). For example, the destructor for the class simple
can be defined as below:
38

about:blank 38/90
1/7/24, 4:44 PM OOPS Notes

~simple ()
{
……………
}
A destructor never takes any arguments nor does it return value. It will be invoked implicitly
by the compiler upon exit from the program to clean up storage that is no longer accessible. It
is good practice to declare destructors in a program since it releases memory space for future
use.
EXAMPLE
#include<iostream.h>
#include<conio.h>
int count=0;
class dstr
{
public:
dstr()
{
count++;
cout<<"No. of objects created ="<<count<<endl;
}
~dstr()
{
cout<<"No. of objects destroyed ="<<count<<endl;
count--;
}
};
void main()
{
clrscr();
cout<<"enter main\n";
dstr d1,d2,d3,d4;
{
cout<<"Block 1\n";
dstr d5;
39

about:blank 39/90
1/7/24, 4:44 PM OOPS Notes

}
{
cout<<"Block 2\n";
dstr d6;
}
}
OUTPUT
enter main
No. of objects created =1
No. of objects created =2
No. of objects created =3
No. of objects created =4
Block 1
No. of objects created =5
No. of objects destroyed =5
Block 2
No. of objects created =5
No. of objects destroyed =5
No. of objects destroyed =4
No. of objects destroyed =3
No. of objects destroyed =2
No. of objects destroyed =1

40

about:blank 40/90
1/7/24, 4:44 PM OOPS Notes

UNIT III
INHERITANCE
Reusability is important feature of c++. It is always nice if we could reuse something
and already exists rather than trying to create the same all over again. It would not only save
time and money but also reduce frustration and increase reliability. For example, the reuse of
a class that has already been tested, debugged and used many times can save the effort of
developing and testing the same again.
C++ strongly supports the concept of reusability. The C++ classes can be reused in
several ways. Once a class has been written and tested, it can be adapted by other
programmers to suit their requirements. This is basically done by creating new classes,
reusing the properties of the existing ones. The mechanism of deriving new classes from old
ones is called inheritance. The old class is known as base class and new one is called derived
class.
The derived class inherits some or all properties of base class. A class can also inherit
from more than one class or from one level. A derived class with only one base class is called
single inheritance and one with several base classes is called multiple inheritance. on the
other hand, the traits of one class may be inherited by more than one class. This is known as
hierarchical inheritance. the mechanism of deriving new class from another derived class is
known as multilevel inheritance.
Following fig shows the types of inheritance.

Single inheritance

Multiple inheritance Hierarchical inheritance

41

about:blank 41/90
1/7/24, 4:44 PM OOPS Notes

Multilevel inheritance Hybrid inheritance


DEFINING DERIVED CLASSES
A derived class is defined by specifying its relationship with the base class in
addition to its own details. The general form of defining derived class is
class derived-clas- name : visibility-mode base-class-name
{
…………………
…………………//members of derived class
………………….
};
The colon indicates that the derived-class-name is derived from the base-class-name. the
visibility mode is optional and, if present, may be either private or public. The default
visibility-mode is private. Visibility-mode specifies whether the features of the base class
areptivately derived or publicly derived.
Examples
class D1 : private B1 //private derivation
{
………………..
………………..
};
class D1 : public B1 //public derivation
{
………………..
………………..
};
class D1 : B1 //private derivation by default
{
………………..
………………..
42

about:blank 42/90
1/7/24, 4:44 PM OOPS Notes

};

When a base class is privately inherited by a derived class, public members of the base class
becomes private members of the derived class and therefore the public members of the base
class can only be accessed by the member functions of the derived class. They are
inaccessible to the objects of the derived class.
On the other hand when a base class is publicly inherited by a derived
class, public members of the base class becomes public members of the derived class and
therefore the public members of the base class are accessible to the objects of the derived
class. In both the cases private members are not inherited and therefore private members of
the base class will never become the members of derived class.
SINGLE INHERITANCE (PUBLIC DERIVATION)
class B
{
public:
int a,b;
void getdata(int x, int y)
{
a=x;
b=y;
}
int mult()
{
return (a * b);
}
};
class D : public B
{
int c;
public:
void display()
{
c=5;
cout<<”result=”<<c* mult();
43

about:blank 43/90
1/7/24, 4:44 PM OOPS Notes

}
};
void main()
{
D b1;
b1.getdata(10,20);
b1.display();
}

OUTPUT
RESULT=1000

SINGLE INHERITANCE (PRIVATE DERIVATION)


class B
{
public:
int a,b;
void getdata(int x, int y)
{
a=x;
b=y;
}
int mult()
{
return (a * b);
}
};
class D : private B
{
int c;
public:
void display()
{
getdata(10,20);
44

about:blank 44/90
1/7/24, 4:44 PM OOPS Notes

c=5;
cout<<”result=”<<c* mult();
}
};
void main()
{
D b1;
b1.display();
}

OUTPUT
result=1000
MAKING A PRIVATE MEMBER INHERITABLE
We know that a private member of a base class can’t be inherited and therefore it is
not available for the derived class directly. Then if we needs private data to be inherited then
C++provides a third visibility modifier, protected , which serve a limited purpose in
inheritance. A member declared as protected is accessible by the member functions within its
class and any class immediately derived from it. It can’t be accessed by the functions outside
these two classes. A class can now use all the three visibility modes as illustrated below.
class simple
{
private: //optional
………………… //visible to member functions within its class
………………….
protected: // visible to member functions within its own and derived class
…………………..
…………………..
public : //vi
sible to all functions in the program
……………………..
…………………….
};

Visibility of inherited members are as follows.


45

about:blank 45/90
1/7/24, 4:44 PM OOPS Notes

Base class visibility Derived class visibility


Public derivation private derivation
Private not inherited not inherited
Protected protected private
Public public private
MULTILEVEL INHERITANCE

A Base class

B Intermediate Class

C Child class

In above fig A serves as a base class for the derived class C. the B is known as intermediate
base class since it provides link for the inheritance between A and C. The chain ABC is
known as inheritance path. A derived class with multilevel inheritance is declared as follows:
Class A { ………………..};
Class B: public A { ……………..};
Class C: public B { …………….. };
This process can be extended to any number of levels.
Example
#include<iostream.h>
class student
{
protected:
int rno;
public:
void getrno()
{
cout<<”Enter roll number”;
cin>>rno;

46

about:blank 46/90
1/7/24, 4:44 PM OOPS Notes

}
void putrno()
{
cout<<”Roll number: “<<rno;
}
};
class test: public student
{
protected:
int m1,m2,m3;
public:
void getmarks()
{
cout<<”Enter merks of 3 subjects”;
cin>>m1>>m2>>m3;
}
void putmarks()
{
cout<<”Computer: “ <<m1;
cout<<”Electronics: “ <<m2;
cout<<”Maths: “ <<m3;
}
};
class result : public test
{
int total;
public:
void display
{
putrno();
putmarks();
total=m1+m2+m3;
cout<<”Total : “<<total;
}
47

about:blank 47/90
1/7/24, 4:44 PM OOPS Notes

};
void main()
{
result R;
R.getrno();
R.getmarks();
R.display();
}

MULTIPLE INHERITANCE
A class can inherit the attributes of two or more classes as shown in following fig. This is
known as multiple inheritance. This allows us to combine the features of several existing
classes as a starting point to define new classes. The syntax for defining
class D : visibility B-1,visibility B-2,…….
{
:::::::::::::::::::::
};
B-1 B-2 B-3

Example
#include<iostream.h>
class student
{
protected:
int rno;
public:
void getrno()
{
cout<<”Enter roll number”;

48

about:blank 48/90
1/7/24, 4:44 PM OOPS Notes

cin>>rno;
}
void putrno()
{
cout<<”Roll number: “<<rno;
}
};
class test
{
protected:
int m1,m2,m3;
public:
void getmarks()
{
cout<<”Enter merks of 3 subjects”;
cin>>m1>>m2>>m3;
}
void putmarks()
{
cout<<”Computer: “ <<m1;
cout<<”Electronics: “ <<m2;
cout<<”Maths: “ <<m3;
}
};
class result : public student , public test
{
int total;
public:
void display
{
putrno();
putmarks();
total=m1+m2+m3;
cout<<”Total : “<<total;
49

about:blank 49/90
1/7/24, 4:44 PM OOPS Notes

}
};
void main()
{
result R;
R.getrno();
R.getmarks();
R.display();
}

HYBRID INHERITANCE
There could be situations where we need to apply two or more types of inheritance to design
a program.

Student

sports
test

result

Example
#include<iostream.h>
class student
{
protected:
int rno;
public:
void getrno()
{
cout<<”Enter roll number”;
cin>>rno;
}
void putrno()
{
50

about:blank 50/90
1/7/24, 4:44 PM OOPS Notes

cout<<”Roll number: “<<rno;


}
};
class test : public student
{
protected:
int m1,m2,m3;
public:
void getmarks()
{
cout<<”Enter merks of 3 subjects”;
cin>>m1>>m2>>m3;
}
void putmarks()
{
cout<<”Computer: “ <<m1;
cout<<”Electronics: “ <<m2;
cout<<”Maths: “ <<m3;
}
};
class sports
{
int sp=5;
void displaysp
{
cout<<”Sports Marks :”<<sp
}
};
class result : public test , public sports
{
int total;
public:
void display
{
51

about:blank 51/90
1/7/24, 4:44 PM OOPS Notes

putrno();
putmarks();
displaysp();
total=m1+m2+m3+sp;
cout<<”Total : “<<total;
}
};
void main()
{
result R;
R.getrno();
R.getmarks();
R.display();
}

CONSTRUCTORS IN DERIVED CLASSES


One important thing to note is that , as long as no base class constructor takes any
arguments, the derived class need not have a constructor function. However , if any base class
contains a constructor with one or more constructor, then it is mandatory for the derived class
to have a constructor and pass the arguments to the base class constructor.
In case of multiple inheritance, the base classes are constructed in the order in which they
appear in the declaration of the derived class. Similarly, in a multilevel inheritance, the
constructors will be executed in the order of inheritance.
Since the derived class takes the responsibility of supplying values to its base classes, we
supply the initial values that are required by all the classes together, when a derived class
object is declared. The derived class constructor receives the entite list of values as its
arguments. And passes them on to the base constructors in the order in which they are
declared in the derived class. The base constructors are executed first before executing the
statements in the body of derived class constructor.
The general form of defining a derived constructor is
Derived-constructor ( arglist1,arglist2,………arglistd) : base1(arglist1), base2(arglist2),
……….
{
Body of derived class constructor
52

about:blank 52/90
1/7/24, 4:44 PM OOPS Notes

}
The header line contains two parts separated by colon. The first part provides the declaration
of arguments that are passed to derived constructor and second part lists the function calls to
the base constructors.
Base1(arglist1),base2(arglist2),…. Are function calls to base constructors base1(), base2(),
….. and therefore arglist1, arglist2 etc. represents the actual parameters that are passed to the
base constructors.
Example
class B1
{
int b1,b2;
public:
B1(int x,int y)
{
b1=x; b2=y;
}
void showb1()
{
cout<<”b1=”<<b1<<”b2=”<<b2;
}
};
class B2
{
int a1,a2;
public:
B2(int x,int y)
{
a1=x; a2=y;
}
void showa1()
{
cout<<”a1=”<<a1<<”a2=”<<a2;
}
};
53

about:blank 53/90
1/7/24, 4:44 PM OOPS Notes

class D : public B1, public B2


{
int c;
public:
D(int x1,int x2,int x3,int x4,int x5) :B1(x1,x2),B2(x3,x4)
{
c=x5;
}
}
void showc()
{
cout<<”c=”<<c;
}
};
void main()
{
D d1(1,5,3,7,8);
D1.showb1()
D1.showb1();
D1.showc();
}
Output
b1=1 b2=5 a1=3 a2=7 c=8
Upcasting and Downcasting in C++
When we convert one data type into another type, the process is called typecasting. But the,
Upcasting and downcasting are the types of object typecasting. Suppose the Parent and Child
class has two types of object, parent_obj and child_obj, which can be cast into the Parent to
Child and Child to Parent using the Upcasting and Downcasting in C++ programming.

Upcasting

It is the process to create the derived class's pointer or reference from the base class's pointer
or reference, and the process is called Upcasting. It means the upcasting used to convert the
reference or pointer of the derived class to a base class. Upcasting is safe casting as compare

54

about:blank 54/90
1/7/24, 4:44 PM OOPS Notes

to downcasting. It allows the public inheritance that implicitly cast the reference from one
class to another without an explicit typecast. By default, the upcasting create is-a relationship
between the base and derived classes.
1. Base *ptr = &derived_obj;
The derived class can inherit all the base class properties that include data members and the
member function to execute the function using the derived class object, as we do with a base
object.
Program to demonstrate the Upcasting in C++

Let's consider an example to convert the derived class's pointer to the base class's pointer in
the C++ programming language.
class Base
{
public:
void disp()
{
cout << " It is the Super function of the Base class ";
}
};
class derive : public Base
{
public:
void disp()
{
cout << "\n It is the derive class function ";
}
};
int main ()
{
Base *ptr;
derive obj; // create object of derive class
ptr = &obj; // assign the obj address to ptr variable
// create base class's reference
Base &ref = obj;

55

about:blank 55/90
1/7/24, 4:44 PM OOPS Notes

// Or
// get disp() function using pointer variable
ptr->disp();
return 0;
}
Output
It is the Super function of the Base class

Downcasting

The Downcasting is an opposite process to the upcasting, which converts the base class's
pointer or reference to the derived class's pointer or reference. It manually cast the base
class's object to the derived class's object, so we must specify the explicit typecast. The
downcasting does not follow the is- a relation in most of the cases. It is not safe as upcasting.
Furthermore, the derived class can add new functionality such as; new data members and
class member's functions that use these data members. Still, these functionalities could not
apply to the base class.
Derived *d_ptr = &b_obj;
Program to demonstrate the downcasting in C++

Let's create an example to downcast the base class's object to the derived class in the C++
programming language.
#include <iostream>
using namespace std;
class Parent
{
public:
void base()
{
cout << " It is the function of the Parent class "<< endl;
}
};
class Child : public Parent
{

56

about:blank 56/90
1/7/24, 4:44 PM OOPS Notes

public:
void derive()
{
cout << " it is the function of the Child class " <<endl;
}
};

int main ()
{
Parent pobj; // create Parent's object
Child *cobj; // create Child's object
// explicit type cast is required in downcasting
cobj = (Child *) &pobj;
cobj -> derive();
return 0;
}
Output
It is the function of the Child class
Program to demonstrate the upcasting and the downcasting in C++

Let's consider an example to use the downcasting and the upcasting in C++ to convert the
base class to derive and the derived class's object to the base class.
#include <iostream>
using namespace std;
class Parent {
private:
int id;
public:
void showid ()
{
cout << " I am in the Parent class " << endl;
}
};
class Myson : public Parent {

57

about:blank 57/90
1/7/24, 4:44 PM OOPS Notes

public:
void disp ()
{
cout << " I am in the Myson class " << endl;
}
};
int main ( int argc, char * argv[])
{
// create object of the Parent class
Parent par_obj;
// create object of the Myson class
Myson my_obj;
// upcast - here upcasting can be done implicitly
Parent *ptr1 = &my_obj; // base class's reference the derive class's object
// downcast - here typecasting is done explicitly
Myson *ptr2 = (Myson *) &par_obj;
// Upcasting is safe:
ptr1->showid();
ptr2->showid();
// downcasting is unsafe:
ptr2->disp();
getchar();
return 0;
}
Output
I am in the Parent class
I am in the Parent class
I am in the Myson class

58

about:blank 58/90
1/7/24, 4:44 PM OOPS Notes

UNIT IV
What is Polymorphism?

Polymorphism is one of the most important concepts of Object-Oriented Programming


(OOPs). For a language considered to be an OOP language, it must support polymorphism.
You can describe the word polymorphism as an object having many forms. Polymorphism is
the notion that can hold up the ability of an object of a class to show different responses. In
other words, you can say that polymorphism is the ability of an object to be represented in
over one form.
Types of Polymorphism

Based on the functionality, you can categorize polymorphism into two types:
 Compile-Time Polymorphism

When the relationship between the definition of different functions and their function calls, is
determined during the compile-time, it is known as compile-time polymorphism. This type of
polymorphism is also known as static or early binding polymorphism. All the methods of
compile-time polymorphism get called or invoked during the compile time.
You can implement compile-time polymorphism using function overloading and operator
overloading. Method/function overloading is an implementation of compile-time
polymorphism where the same name can be assigned to more than one method or function,
having different arguments or signatures and different return types. Compile-time
polymorphism has a much faster execution rate since all the methods that need to be executed
are called during compile time. However, it is less preferred for handling complex problems
since all the methods and details come to light only during the compile time. Hence,
debugging becomes tougher.
The implementation of compile-time polymorphism is achieved in two ways:
 Function overloading
 Operator overloading
Before discussing them, it is essential to understand their other counterpart which is runtime
polymorphism.
 Runtime Polymorphism

In runtime polymorphism, the compiler resolves the object at run time and then it decides
which function call should be associated with that object. It is also known as dynamic or late
binding polymorphism. This type of polymorphism is executed through virtual functions and

59

about:blank 59/90
1/7/24, 4:44 PM OOPS Notes

function overriding. All the methods of runtime polymorphism get invoked during the run
time.
Method overriding is an application of run time polymorphism where two or more functions
with the same name, arguments, and return type accompany different classes of the same
structure. This method has a comparatively slower execution rate than compile-time
polymorphism since all the methods that need to be executed are called during run time.
Runtime polymorphism is known to be better for dealing with complex problems since all the
methods and details turn up during the runtime itself.
The implementation of run time polymorphism can be achieved in two ways:
 Function overriding
 Virtual functions
C++ Function Overriding
In this tutorial, we will learn about function overriding in C++ with the help of examples.
As we know, inheritance is a feature of OOP that allows us to create derived classes from a
base class. The derived classes inherit features of the base class.
Suppose, the same function is defined in both the derived class and the based class. Now if
we call this function using the object of the derived class, the function of the derived class is
executed.
This is known as function overriding in C++. The function in derived class overrides the
function in base class.

Example 1: C++ Function Overriding

// C++ program to demonstrate function overriding


#include <iostream>
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
class Derived : public Base {
public:
void print() {

60

about:blank 60/90
1/7/24, 4:44 PM OOPS Notes

cout << "Derived Function" << endl;


}
};
int main() {
Derived derived1;
derived1.print();
return 0;
}
Early binding and Late binding in C++
The binding means the process of converting identifiers into addresses. For each variables
and functions this binding is done. For functions it is matching the call with the right
function definition by the compiler. The binding is done either at compile time or at runtime.
Early Binding

This is compile time polymorphism. Here it directly associates an address to the function
call. For function overloading it is an example of early binding.
Example

#include<iostream>
using namespace std;
class Base {
public:
void display() {
cout<<" In Base class" <<endl;
}
};
class Derived: public Base {
public:
void display() {
cout<<"In Derived class" << endl;
}
};
int main(void) {
Base *base_pointer = new Derived;
base_pointer->display();

61

about:blank 61/90
1/7/24, 4:44 PM OOPS Notes

return 0;
}
Output

In Base class
Late Binding

This is run time polymorphism. In this type of binding the compiler adds code that identifies
the object type at runtime then matches the call with the right function definition. This is
achieved by using virtual function.
Example

#include<iostream>
class Base {
public:
virtual void display() {
cout<<"In Base class" << endl;
}
};
class Derived: public Base {
public:
void display() {
cout<<"In Derived class" <<endl;
}
};
int main() {
Base *base_pointer = new Derived;
base_pointer->display();
return 0;
}
Output

In Derived class
VIRTUAL BASE CLASSES
Consider a situation where all the three kinds of inheritances, namely multilevel, multiple and
hierarchical inheritance , are involved. This is illustrated in following fig.

62

about:blank 62/90
1/7/24, 4:44 PM OOPS Notes

grandparent

Parent1 Parent2
irect base classes ‘parent1’ and ‘parent2’ which themselves have a
common base class ‘grandparent’ . the ‘child’ inherites the traits of grandparent via two
separate paths. Grandparent is also called as indirect base class.
Child
Inheritance by child might pose some problems. All the public and protected members of
grandparent are inherited into child twice , first via parent1 and second via parent2. This
means child would have duplicate set of the members inherited from grandparent. This
introduces ambiguity and must be resolved.
This duplication of inherited members due to these multiple paths can be avoided by
making common base class as virtual base class while declaring the direct or intermediate
base classes as shown below.
class A //grandparent
{
…………………
…………………
};
class B1 : public virtual A //parent1
{
…………………
…………………
};
class B2 : virtual public A //parent2
{
…………………
…………………
};
class C : public B1, public B2
{
…………………
…………………
};

63

about:blank 63/90
1/7/24, 4:44 PM OOPS Notes

When a class is made a virtual base class, C++ takes necessary care to see that only one copy
of that class is inherited, regardless of how many inheritance paths exists between the virtual
base class and a derived class. Consider the following example

student

test sports

result
#include<iostream.h>
class student
{
protected:
int rno;
public:
void getrno()
{
cout<<”Enter roll number”;
cin>>rno;
}
void putrno()
{
cout<<”Roll number: “<<rno;
}
};
class test : virtual public student
{
protected:
int m1,m2,m3;
public:
void getmarks()
{
cout<<”Enter merks of 3 subjects”;
64

about:blank 64/90
1/7/24, 4:44 PM OOPS Notes

cin>>m1>>m2>>m3;
}
void putmarks()
{
cout<<”Computer: “ <<m1;
cout<<”Electronics: “ <<m2;
cout<<”Maths: “ <<m3;
}
};
class sports :public virtual student
{
int sp=5;
void displaysp
{
cout<<”Sports Marks :”<<sp
}
};
class result : public test , public sports
{
int total;
public:
void display
{
putrno();
putmarks();
displaysp();
total=m1+m2+m3+sp;
cout<<”Total : “<<total;
}
};
void main()
{
result R;
R.getrno();
65

about:blank 65/90
1/7/24, 4:44 PM OOPS Notes

R.getmarks();
R.display();
}

ABSTRACT CLASSES
An abstract class is one that is not used to create objects. An abstract class is designed only to
act as a base class. It is a design concept in program development and provides a base upon
which other classes may be built. In above example, student class is abstract class since it
was not used to create objects.
OPERATOR OVERLOADING
Operator overloading is one of the exciting features of C++ language. It is an important
technique that has enhanced the power of extensibility of C++. We know that C++ tries to
make the user defined data type behaves in much the same way as the built-in types. For
example, C++ permits us to add two variable of user defined data types(objects) with the
same syntax that is applied to the basic types. This means that C++ has the ability to provide
the operators with a special meaning for a data type. The mechanism of giving such a special
meaning to operators is called operator overloading. We can overload all the C++ operators
except the following:
 Class member access opearator (. , .*)
 Scope resolution opearator (::)
 Size operator (sizeof)
 Conditional operator (?:)
Although the semantics of an operator can be extended, we cannot change its syntax, the
grammatical rules that govern its use such as the number of operands, precedence, and
associativity. For example , * operator will enjoy higher precedence than + operator.

Rules for operator overloading


 Only existing operators can be overloaded. New operators cannot be created.
 The basic meaning of an operator cannot be changed. That is the plus operator cannot be
used to subtract one value from the other.
 Overloaded operator follow the syntax rules of the original operators. They cannot be
overridden.
 There are some operators that cannot be overloaded. They are Size of, . ,: :,?:.
66

about:blank 66/90
1/7/24, 4:44 PM OOPS Notes

 The overloaded operator must have atleast one operand that is of user defined type.
 Unary operators, overload by means of a member function, take no explicit arguments
and return no explicit values but those overloaded by means of a friend function, take one
reference argument.
 Binary operators overloaded through a member function take one explicit argument and
those which are overloaded through a friend function take two explicit arguments.
 When using binary operator overloaded through a member function, the left hand operand
must be an object of the relevant class.
 Binary arithmetic operators such as +,-,*,and / must explicitly return a value. They must
not attempt to change their own arguments.
DEFINING OPERATOR OVERLOADING
To define additional task to an operator, we must specify what it means in relation to
the class to which the operator applied. This is done with the help of a special function called
operator function. The general form of this function is:
Return-type class-name:: operator op(arg-list)
{
Function-body
}
Where return-type is the type of value returned by the specified operation and op is the
operator being overloaded. The op is preceded by the keyword operator. Operator op is the
function name.
Operator functions must be either member function or friend function. A basic
difference between them is that a friend function will have only one argument for unary
operators and two for binary operators. While member function will have no argument for
unary operators and one for binary operators. This is because the object used to invoke the
member function is passed implicitly and therefore is available for the member function. This
is not the case with friend function. Arguments may be passed by value or reference.
Operator functions are declared in the class using prototypes as follows:
complex operator +(complex); //complex addition using member function
friend complex operator +(complex,complex); //complex addition using friend
fn
int operator ==(complex); //comparison
friend int operator ==(complex , complex); //comparison
friend complex operator –(complex) //unary minus
67

about:blank 67/90
1/7/24, 4:44 PM OOPS Notes

complex operator –( ) //unary minus


where complex is a class containing real and imaginary part of a complex number.
The process of overloading involves the following steps.
1. First create a class that defines the data type that is to be used in the overloading
operation.
2. Declare the operator function operator op() in the public part of the class . it may be
either friend function or member function.
3. Define the operator function to implement the required operation.
Overloaded operator function can be invoked by expressions sush as
op x or x op
for unary operators and
x op y
for binary operators.

OVERLOADING UNARY OPERATORS USING MEMBER FUNCTION


Let us consider unary minus operator( - ). This operator changes the sign of data items of the
objects. It is illustrated follows.
#include <iostream.h>
class simple
{
int x,y,z;
public:
void getdata(int , int , int);
void putdata()
void operator –();
};
void simple:: getdata(int l, int m, int n)
{
x=l;
y=m;
z=n;
}
void simple:: putdata()
{
68

about:blank 68/90
1/7/24, 4:44 PM OOPS Notes

cout<< x<<”\t“<<y<<”\t”<<z<<endl;
}
void simple::operator –()
{
x=-x;
y=-y;
z=-z;
}
void main()
{
simple s;
s.getdata(10,-21,-12);
cout<<”before overloading:;
s.putdata();
-s;
cout<<”after overloading:;
s.putdata();
}
This program produces following output
before overloading:10 -21 -12
after overloading:-10 21 12
In above example since operator function is a member function, in the statement
-s;
Object s calls the operator function –(). Therefore members of s will be available to the
function, which then changes the sign of members.

OVERLOADING UNARY OPERATORS USING FRIEND FUNCTION


Consider the following example which overloads – operator using friend function .
#include <iostream.h>
class simple
{
int x,y,z;
public:
void getdata(int , int , int);
69

about:blank 69/90
1/7/24, 4:44 PM OOPS Notes

void putdata();
friend void operator –(simple &s);
};
void simple:: getdata(int l, int m, int n)
{
x=l;
y=m;
z=n;
}
void simple:: putdata()
{
cout<< x<<”\t“<<y<<”\t”<<z<<endl;
}
void operator –(simple &s)
{
s.x=-s.x;
s.y=-s.y;
s.z=-s.z;
}
void main()
{
simple s;
s.getdata(10,-21,-12);
cout<<”before overloading:;
s.putdata();
-s;
cout<<”after overloading:;
s.putdata();
}
This program produces following output
before overloading:10 -21 -12
after overloading:-10 21 12
In above example , the statement
-s;
70

about:blank 70/90
1/7/24, 4:44 PM OOPS Notes

Calls the operator function –() and passes object s as argument to the function. Therefore
members of s will be available to the function, which then changes the sign of members.

OVERLOADING BINARY OPERATORS USING MEMBER FUNCTION


Consider the following example which overloads + operator to calculate addition of
complex numbers using member function .
#include<iostream.h>
class complex
{
int x,y;
public:
void input(int a, int b);
void display();
complex operator +(complex c);
}
void complex::display()
{
cout<<x<<”+”<<y<<”i”<<endl;
}
void complex::input(int a,int b)
{
x=a;
y=b;
}
complex complex::operator +(complex c)
{
complex c3;
c3.x=x+c.x;
c3.y=y+c.y;
return c3;
}
void main()
{
complex c1,c2,c3;
71

about:blank 71/90
1/7/24, 4:44 PM OOPS Notes

c1.input(1,2)
c2.input(3,5);
c3=c1+c2;
cout<<”complex 1=”;
c1.display();
cout<<”complex 2=”;
c2.display();
cout<<”addition=”;
c3.display()
}
above program produces following output
complex 1=1+2i
complex2=3+5i
addition=4+7i
in above example , the statement
c3=c1+c2;
calls the operator function +() as it is a member function, object on L.H.S. of operator + calls
the function and object on R.H.S. of operator is passed to the function as argument. Therefore
, in the operator function, the data members of c1 are accessed directly and data members of
c2 are accessed using dot operator. Thus both the objects are available for the function.

OVERLOADING BINARY OPERATORS USING FRIEND FUNCTION


Consider the following example which overloads + operator to calculate addition of
complex numbers using friend function .
#include<iostream.h>
class complex
{
int x,y;
public:
void input(int a, int b);
void display();
friend complex operator +(complex c1,complex c2);
}
void complex::display()
72

about:blank 72/90
1/7/24, 4:44 PM OOPS Notes

{
cout<<x<<”+”<<y<<”i”<<endl;
}
void complex::input(int a,int b)
{
x=a;
y=b;
}
complex operator +(complex c1,complex c2)
{
complex c3;
c3.x=c1.x+c2.x;
c3.y=c1.y+c2.y;
return c3;
}
void main()
{
complex c1,c2,c3;
c1.input(1,2)
c2.input(3,5);
c3=c1+c2;
cout<<”complex 1=”;
c1.display();
cout<<”complex 2=”;
c2.display();
cout<<”addition=”;
c3.display()
}
above program produces following output
complex 1=1+2i
complex2=3+5i
addition=4+7i
in above example , the statement
c3=c1+c2;
73

about:blank 73/90
1/7/24, 4:44 PM OOPS Notes

calls the operator function +() and both the objects c1 and c2 passes as arguments to the
operator function.
VIRTUAL FUNCTION
Polymorphism refers to the property by which objects belonging to different classes
are able to respond to the same message , but in different forms. An essential requirement of
polymorphism is therefore the ability to refer to objects without any regard to their classes.
Here we use the base class pointer to refer to all derived objects. But we know that a base
pointer , even when it is made to contain the address of a derived class , always executes the
function in the base class. The compiler simply ignores the contents of the pointer and
chooses the member function that matches the type of the pointer. Hence to overcome this
problem , virtual functions are used.
When we use the same function name in both base and derived classes, the function in
base class is declared as virtual using the keyword virtual preceding the its normal
declaration. When a function is made virtual, C++ determines which function to use at
runtime based on the type of the object pointed to by the base pointer, rather than the type of
the pointer. Thus by making the use of base pointer to point to different objects, we can
execute different versions of virtual function.
Example
class base
{
public:
void display()
{
cout<<”display base\n”;
}
virtual void show()
{
cout<<”show base\n”;
}
};
class derived : public base
{
public:
void display()
74

about:blank 74/90
1/7/24, 4:44 PM OOPS Notes

{
cout<<”display derived\n”;
}
void show()
{
cout<<”show derived\n”;
}
};
void main()
{
base b,*bptr;
derived d;
bptr=&b;
cout<<”bptr points to base class object\n”;
bptr->display();
bptr->show();
bptr=&d;
cout<<”bptr points to derived class object\n”;
bptr->display();
bptr->show();
}
OUTPUT
bptr points to base class object
display base
show base
bptr points to derived class object
display base
show derived
Rules for virtual function
 Virtual functions must be members of some class
 They can’t be static members
 They are accessed by using base pointers
 A virtual function can be a friend of another class.
 A base pointer can point to any type of derived object , the reverse is not true.
75

about:blank 75/90
1/7/24, 4:44 PM OOPS Notes

 A virtual function can be a friend of another class.


Pure virtual functions
It is normal practice to declare a function virtual inside a base class and redefine it in the
derived classes. The function inside the base class only serves as a placeholder since we don’t
create an object of base class. Hence we defined empty function in base class. Such functions
are called “do nothing “ function.
A “do nothing “ function is defined as follows
virtual void show( )= 0;
such functions are called pure virtual function. A pure virtual function is a function declared
in a base class that has no definition relative to base class. In such cases, the compiler require
each derived class to either define the function or redeclare it as a pure virtual function. But a
class containing pure virtual function can’t be used to declare any objects of its own.

76

about:blank 76/90
1/7/24, 4:44 PM OOPS Notes

UNIT V
Static data member
A static data member has certain special characteristics:
 It is initialized to zero when the first object of its class is created.
 Only one copy of that member is created and is shared by all the objects of that class.
No matter how many objects are created.
 It is visible only within the class, but its lifetime is entire program
Static variables are normally used to maintain values common to the entire class. For
example, a static data member can be used as counter that records the occurrences of all the
objects. Static data members are declared as
static data-type var;
e.g static int c;
in the class definition. Also the scope and type must be defined outside the class definition as
follows
data-type class-name : : var;
e.g. int student : : c;
this is necessary because the static data members are stored separately rather than as part of
an object.
Following fig shows the sharing of static data member

Object1 Object2 Object3

Static variable

Static member function


Like, static data member we can also have static member function. A member function that is
declared static has the following properties.
 A static function can have access to only other static data members declared in the
same class
 A static data member function can be called using the class name instead of object as
follows
Class-name : : function-name( );

77

about:blank 77/90
1/7/24, 4:44 PM OOPS Notes

Following example shows the use of static data member and member function
class simple
{
int x;
static int c;
public:
void setdata( int a)
{
x=a;
c++;
}
static void showc()
{
cout<<”Count=”<<c<<endl;
}
};
int simple:: c;
void main()
{
simple s1, s2;
s1.setdata(3);
s1.setdata(4);
simple s3;
s3.setdata(1);
simple : : showcode( ) ;
}

Output
Count=1
Count=2
Count=3

78

about:blank 78/90
1/7/24, 4:44 PM OOPS Notes

C++ Templates
A C++ template is a powerful feature added to C++. It allows you to define the generic
classes and generic functions and thus provides support for generic programming. Generic
programming is a technique where generic types are used as parameters in algorithms so that
they can work for a variety of data types.
Templates can be represented in two ways:
o Function templates
o Class templates

Function Templates:
We can define a template for a function. For example, if we have an add() function, we can
create versions of the add function for adding the int, float or double type values.
Class Template:
We can define a template for a class. For example, a class template can be created for the
array class that can accept the array of various types such as int array, float array or double
array.

Function Template

o Generic functions use the concept of a function template. Generic functions define a
set of operations that can be applied to the various types of data.
o The type of the data that the function will operate on depends on the type of the data
passed as a parameter.
o For example, Quick sorting algorithm is implemented using a generic function, it can
be implemented to an array of integers or array of floats.
o A Generic function is created by using the keyword template. The template defines
what function will do.
Syntax of Function Template

1. template < class Ttype> ret_type func_name(parameter_list)


2. {
3. // body of function.
4. }

79

about:blank 79/90
1/7/24, 4:44 PM OOPS Notes

Where Ttype: It is a placeholder name for a data type used by the function. It is used within
the function definition. It is only a placeholder that the compiler will automatically replace
this placeholder with the actual data type.
class: A class keyword is used to specify a generic type in a template declaration.
Let's see a simple example of a function template:
#include <iostream.h>
template<class T> T add(T a,T b)
{
T result = a+b;
return result;
}
int main()
{
int i =2;
int j =3;
float m = 2.3;
float n = 1.2;
cout<<"Addition of i and j is :"<<add(i,j);
cout<<"Addition of m and n is :"<<add(m,n);
return 0;
}
Output:
Addition of i and j is :5
Addition of m and n is :3.5

In the above example, we create the function template which can perform the addition
operation on any type either it can be integer, float or double.
Function Templates with Multiple Parameters

We can use more than one generic type in the template function by using the comma to
separate the list.
Syntax

template<class T1, class T2,.....>


return_type function_name (arguments of type T1, T2....)

80

about:blank 80/90
1/7/24, 4:44 PM OOPS Notes

{
// body of function.
}
In the above syntax, we have seen that the template function can accept any number of
arguments of a different type.
Let's see a simple example:
#include <iostream.h>
template<class X,class Y>
void fun(X a,Y b)
{
cout << "Value of a is : " <<a<< endl;
cout << "Value of b is : " <<b<< endl;
}
void main()
{
fun(15,12.3);
fun(‘@’,3.4);
}

Output:
Value of a is : 15
Value of b is : 12.3
In the above example, we use two generic types in the template function, i.e., X and Y.
Overloading a Function Template

We can overload the generic function means that the overloaded template functions can differ
in the parameter list.
Let's understand this through a simple example:
#include <iostream.h>
template<class X> void fun(X a)
{
cout << "Value of a is : " <<a<< endl;

81

about:blank 81/90
1/7/24, 4:44 PM OOPS Notes

}
template<class X,class Y> void fun(X b ,Y c)
{
cout << "Value of b is : " <<b<< endl;
cout << "Value of c is : " <<c<< endl;
}
int main()
{
fun(10);
fun(20,30.5);
fun(5.8,7);
return 0;
}
Output:
Value of a is : 10
Value of b is : 20
Value of c is : 30.5
Value of b is : 5.8
Value of c is : 7

In the above example, template of fun() function is overloaded.


Restrictions of Generic Functions

Generic functions perform the same operation for all the versions of a function except the
data type differs. Let's see a simple example of an overloaded function which cannot be
replaced by the generic function as both the functions have different functionalities.
Let's understand this through a simple example:
#include <iostream>
void fun(double a)
{
cout<<"value of a is : "<<a<<'\n';
}
void fun(int b)
{

82

about:blank 82/90
1/7/24, 4:44 PM OOPS Notes

if(b%2==0)
{
cout<<"Number is even";
}
else
{
cout<<"Number is odd";
}
}
int main()
{
fun(4.6);
fun(6);
return 0;
}
Output:
value of a is : 4.6
Number is even
In the above example, we overload the ordinary functions. We cannot overload the generic
functions as both the functions have different functionalities. First one is displaying the value
and the second one determines whether the number is even or not.

CLASS TEMPLATE

Class Template can also be defined similarly to the Function Template. When a class uses
the concept of Template, then the class is known as generic class.
Syntax

template<class Ttype>
class class_name
{
.
}

83

about:blank 83/90
1/7/24, 4:44 PM OOPS Notes

Ttype is a placeholder name which will be determined when the class is instantiated. We can
define more than one generic data type using a comma-separated list. The Ttype can be used
inside the class body.
Now, we create an instance of a class
1. class_name<type> ob;
where class_name: It is the name of the class.
type: It is the type of the data that the class is operating on.
ob: It is the name of the object.
Let's see a simple example:
#include <iostream.h>
template<class T>
class A
{
public:
T num1, num2 ;
A(T x,T y)
{
num1=x;
num2=y;
}
void add()
{
cout << "Addition of num1 and num2 : " << num1+num2<<endl;
}
};
int main()
{
A<int> d(2,3);
d.add();
A<float> d1(3.6,6.7)
d1.add();
return 0;
}
Output:
84

about:blank 84/90
1/7/24, 4:44 PM OOPS Notes

Addition of num1 and num2 : 5


Addition of num1 and num2 : 10.3

In the above example, we create a template for class A. Inside the main() method, we create
the instance of class A named as, 'd'.
CLASS TEMPLATE WITH MULTIPLE PARAMETERS

We can use more than one generic data type in a class template, and each generic data type is
separated by the comma.
Syntax

template<class T1, class T2, ......>


class class_name
{
// Body of the class.
}
Let's see a simple example when class template contains two generic data types.
#include <iostream.h>
template<class T1, class T2>
class A
{
T1 a;
T2 b;
public:
A(T1 x,T2 y)
{
a = x;
b = y;
}
void display()
{
cout << "Values of a and b are : " << a<<" ,"<<b<<endl;
}
};
int main()

85

about:blank 85/90
1/7/24, 4:44 PM OOPS Notes

{
A<int,float> d(5,6.5);
d.display();
A<float,int> d1(5.8,6);
d1.display();
return 0;
}
Output:
Values of a and b are : 5,6.5
Nontype Template Arguments

The template can contain multiple arguments, and we can also use the non-type arguments In
addition to the type T argument, we can also use other types of arguments such as strings,
function names, constant expression and built-in types. Let' s see the following example:
template<class T, int size>
class array
{
T arr[size]; // automatic array initialization.
};
In the above case, the nontype template argument is size and therefore, template supplies the
size of the array as an argument.
Arguments are specified when the objects of a class are created:
array<int, 15> t1; // array of 15 integers.
array<float, 10> t2; // array of 10 floats.
array<char, 4> t3; // array of 4 chars.
Let's see a simple example of nontype template arguments.
#include <iostream>
using namespace std;
template<class T, int size>
class A
{
public:
T arr[size];
void insert()

86

about:blank 86/90
1/7/24, 4:44 PM OOPS Notes

{
int i =1;
for (int j=0;j<size;j++)
{
arr[j] = i;
i++;
}
}
void display()
{
for(int i=0;i<size;i++)
{
std::cout << arr[i] << " ";
}
}
};
int main()
{
A<int,10> t1;
t1.insert();
t1.display();
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
In the above example, the class template is created which contains the nontype template
argument, i.e., size. It is specified when the object of class 'A' is created.
Points to Remember
o C++ supports a powerful feature known as a template to implement the concept of
generic programming.
o A template allows us to create a family of classes or family of functions to handle
different data types.

87

about:blank 87/90
1/7/24, 4:44 PM OOPS Notes

o Template classes and functions eliminate the code duplication of different data types
and thus makes the development easier and faster.
o Multiple parameters can be used in both class and function template.
o Template functions can also be overloaded.
o We can also use nontype arguments such as built-in or derived data types as template
arguments.

C++ Exception Handling

An exception is a problem that arises during the execution of a program. A C++ exception is
a response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, and throw.
 throw − A program throws an exception when a problem shows up. This is
done using a throw keyword.
 catch − A program catches an exception with an exception handler at the place
in a program where you want to handle the problem. The catch keyword
indicates the catching of an exception.
 try − A try block identifies a block of code for which particular exceptions
will be activated. It's followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using a combination
of the try and catch keywords. A try/catch block is placed around the code that might
generate an exception. Code within a try/catch block is referred to as protected code, and the
syntax for using try/catch as follows −
Try
{
// protected code
}
catch( ExceptionName e1 )
{
// catch block
}

88

about:blank 88/90
1/7/24, 4:44 PM OOPS Notes

catch( ExceptionName e2 )
{
// catch block
} catch( ExceptionName eN ) {
// catch block
}
You can list down multiple catch statements to catch different type of exceptions in case
your try block raises more than one exception in different situations.
Throwing Exceptions

Exceptions can be thrown anywhere within a code block using throw statement. The operand
of the throw statement determines a type for the exception and can be any expression and the
type of the result of the expression determines the type of exception thrown.
Following is an example of throwing an exception when dividing by zero condition occurs −
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
Catching Exceptions

The catch block following the try block catches any exception. You can specify what type of
exception you want to catch and this is determined by the exception declaration that appears
in parentheses following the keyword catch.
try {
// protected code
} catch( ExceptionName e ) {
// code to handle ExceptionName exception
}
Above code will catch an exception of ExceptionName type. If you want to specify that a
catch block should handle any type of exception that is thrown in a try block, you must put an
ellipsis, ..., between the parentheses enclosing the exception declaration as follows −

89

about:blank 89/90
1/7/24, 4:44 PM OOPS Notes

try {
// protected code
} catch(...) {
// code to handle any exception
}
The following is an example, which throws a division by zero exception and we catch it in
catch block.

double division(int a, int b) {


if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}
int main () {
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
} catch (const char* msg) {
cout<< msg << endl;
}
return 0;
}
Because we are raising an exception of type const char*, so while catching this exception,
we have to use const char* in catch block. If we compile and run above code, this would
produce the following result −
Division by zero condition!

90

about:blank 90/90

You might also like