You are on page 1of 64

C++ with Object Oriented Programming

UNIT I
1. Object Oriented Methodology:
1.1. Introduction
1.2. Advantages and Disadvantages of Procedure Oriented Languages
1.3. What is Object Oriented?
1.4. What is Object Oriented Development?
1.5. Benefits and Application of OOPS
2. Principles of OOPS:
2.1. OOPS Paradigm
2.2. Basic Concepts of OOPS: Objects, Classes, Data Abstraction and Data Encapsulation,
Inheritance, Polymorphism, Dynamic Binding, Message Passing

1. Object Oriented Methodology

1.1. Introduction

A program is a sequence of instructions that can be executed by a computer. Every


program is written in some programming language. C++ (pronounced “see-plus-plus”) is
one of the most powerful programming languages available. It gives the programmer the
power to write efficient, structured, object-oriented programs.

C++ is a middle-level programming language developed by Bjarne Stroustrup


starting in 1979 at Bell Labs, as an enhancement to the C language and originally named C
with Classes but later it was renamed C++ in 1983. C++ runs on a variety of platforms,
such as Windows, Mac OS, and the various versions of UNIX.

There are many different languages can be used to program a computer. The most
basic of these is machine Language: machine-language program written for one type of
computer cannot be run on another type of computer without significant alterations. High-
level language, whose instruction set is more compatible with human languages and
human thought processes. Most of these are general-purpose languages such as C. (Some
other popular general-purpose languages are Pascal, FORTRAN and BASIC.) A program
that is written in a high-level language must, however, be translated into machine
language before it can be executed. This is known as compilation or interpretation.

A compiler or interpreter is itself a computer program. It accepts a program written in


a high-level language (e.g., C) as input, and generates a corresponding machine-language
program as output. The original high-level program is called the source program, and the
resulting machine-language program is called the object program. Every computer must
have its own compiler or interpreter for a particular high-level language.

1.2. Advantages and Disadvantages of Procedure Oriented Languages

A computer programming language that executes a set of commands in order is called


procedural Language. It is written as a list of instructions, telling the computer, step-by-
step, what to do. It focuses on the process rather than data. Procedural programming is
fine for small projects. It is the most natural way to tell a computer what to do, and the

Prof. Hemchandra Kumbhar Page 1


C++ with Object Oriented Programming

computer processor’s own language (machine code). Examples of computer procedural


languages are BASIC, C, FORTRAN, and Pascal.

Advantages of Procedural Programming:

1. Its relative simplicity, and ease of implementation of compilers and interpreters


2. The ability to re-use the same code at different places in the program without
copying it.
3. An easier way to keep track of program flow.
4. The ability to be strongly modular or structured.
5. Needs only less memory.

Disadvantages of Procedural languages

1. Procedural codes are very difficult to maintain, if the code grows larger.
2. Importance is given to the sequence of instruction rather than the data.
3. Data is exposed to whole program, so no security for data.
4. A procedural language does not have automatic memory management as like in
Java.
5. Difficult to create new data types reduces extensibility.
6. Difficult to relate with real world objects.

1.3. What is Object Oriented?

Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies the software development and maintenance by providing some
concepts: Object, Class, Inheritance, Polymorphism, Abstraction, Encapsulation, etc.

The core of the pure object-oriented programming is to create an object, in code, that
has certain properties and methods. While designing C++ modules, we try to see whole
world in the form of objects. For example, a car is an object which has certain properties
such as color, number of doors, etc. It also has certain methods such as accelerate, break,
start and stop and so on.

1.4. What is Object Oriented Development?

Approaches use to development of software:

Monolithic Programming Approach: In this approach, the program consists of


sequence of statements that modify data. All the statements of the program are Global
throughout the whole program. The program control is achieved through the use of jumps
i.e. goto statements. In this approach, code is duplicated each time because there is no
support for the function. Data is not fully protected as it can be accessed from any portion
of the program. So this approach is useful for designing small and simple programs. The
programming languages like ASSEMBLY and BASIC follow this approach.

Procedural Programming Approach: This approach is top down approach. In this


approach, a program is divided into functions that perform a specific task. Data is global
and all the functions can access the global data. Program flow control is achieved through
function calls and goto statements. This approach avoids repetition of code which is the
main drawback of Monolithic Approach. The basic drawback of Procedural Programming

Prof. Hemchandra Kumbhar Page 2


C++ with Object Oriented Programming

Approach is that data is not secured because data is global and can be accessed by any
function. This approach is mainly used for medium sized applications. The programming
languages: FORTRAN and COBOL follow this approach.

Structured Programming Approach: The basic principal of structured programming


approach is to divide a program in functions and modules. The use of modules and
functions makes the program more comprehensible (understandable). It helps to write
cleaner code and helps to maintain control over each function. This approach gives
importance to functions rather than data. It focuses on the development of large software
applications. The programming languages: PASCAL and C follow this approach.

Object Oriented Programming Approach: The OOP approach came into existence to
remove the drawback of others approaches. The basic principal of the OOP approach is to
combine both data and functions so that both can operate into a single unit. Such a unit is
called an object. This approach secures data also. Now a day this approach is used mostly
in application. The programming languages: C++ and JAVA follow this approach.

1.5. Benefits and Application of OOPS

Benefits of OOP or advantages

1. It is easy to model a real system as real objects are represented by programming


objects in OOP. The objects are processed by their member data and functions. It is
easy to analyze the user requirements.
2. With the help of inheritance, we can reuse the existing class to derive a new class such
that the redundant code is eliminated and the use of existing class is extended. This
saves time and cost of program.
3. In OOP, data can be made private to a class such that only member functions of the
class can access the data. This principle of data hiding helps the programmer to build a
secure program
4. With the help of polymorphism, the same function or same operator can be used for
different purposes. This helps to manage software complexity easily.
5. Large problems can be reduced to smaller and more manageable. It is easy to partition
the work in a project based on objects.
6. It is possible to have multiple instances of an object to co-exist without any
interference i.e. each object has its own separate member data and function.

Areas of Application of OOP concept:

Applications of OOP are gaining importance in many areas. The most important area is the
user interface design such as windows. The promising areas includes the followings,

1. Real Time Systems Design


2. Simulation and Modeling System
3. Object Oriented Database
4. Object Oriented Distributed Database
5. Client-Server System
6. Hypertext, Hypermedia
7. Neural Networking and Parallel Programming
8. Decision Support and Office Automation Systems
9. Artificial Intelligent(robotics) and Expert Systems

Prof. Hemchandra Kumbhar Page 3


C++ with Object Oriented Programming

2. Principles of OOPS:

2.1. OOPS Paradigm

Object-oriented programming (OOP) is a programming paradigm based upon objects


(having both data and methods) that aims to incorporate the advantages of modularity
and reusability. Objects, which are usually instances of classes, are used to interact with
one another to design applications and computer programs.

The important features of object–oriented programming are:

1. Bottom–up approach in program design


2. Programs organized around objects, grouped in classes
3. Focus on data with methods to operate upon object’s data
4. Interaction between objects through functions
5. Reusability of design through creation of new classes by adding features to existing
classes

Some examples of object-oriented programming languages are C++, Java, Smalltalk,


Delphi, C#, Perl, Python, Ruby, and PHP.

2.2. Basic Concepts of OOPS

The prime purpose of C++ programming was to add object orientation to the C
programming language, which is in itself one of the most powerful programming
languages.

1. Objects: This is the basic unit of object oriented programming. That is both data and
function that operate on data are bundled as a unit called as object. Objects are instances
of class, which holds the data variables declared in class and the member functions work
on these classes.
2. Classes: A class is simply a representation of a type of object (like datatype of any
variable). It is the blueprint, or plan, or template that describes the details of an object. A
class is the blueprint from which the individual objects are created. Class is composed of
three things: a name, attributes (variables), and operations (Methods).
For example: Class of birds, all birds can fly and they all have wings and beaks. So here
flying is a behavior and wings and beaks are part of their characteristics. And there are
many different birds in this class with different names but they all possess this behavior
and characteristics.
Similarly, class is just a blue print, which declares and defines characteristics and
behavior, namely data members and member functions respectively. And all objects of this
class will share these characteristics and behavior.
3. Data Abstraction: Data abstraction refers to, providing only essential information to the
outside world and hiding their background details, i.e., to represent the needed
information in program without presenting the details.
For example, a database system hides certain details of how data is stored and created and
maintained. Similar way, C++ classes provides different methods to the outside world
without giving internal detail about those methods and data.

Prof. Hemchandra Kumbhar Page 4


C++ with Object Oriented Programming

4. Data Encapsulation: Data encapsulation is the concept that binds together the data and
functions that manipulate the data, and that keeps both safe from outside interference and
misuse. Data encapsulation led to the important OOP concept of data hiding.
5. Inheritance: inheritance is the process by which objects of one class acquire the
properties of objects of another class. It supports the concept of hierarchical classification.
Inheritance provides reusability. This means that we can add additional features to an
existing class without modifying it.
6. Polymorphism: polymorphism means ability to take more than one form. An operation
may exhibit different behaviors in different instances. The behavior depends upon the
types of data used in the operation. C++ supports operator overloading and function
overloading. Operator overloading is the process of making an operator to exhibit
different behaviors in different instances is known as operator overloading. Function
overloading is using a single function name to perform different types of tasks.
Polymorphism is extensively used in implementing inheritance.
7. Dynamic Binding: In dynamic binding, the code to be executed in response to function
call is decided at runtime. C++ has virtual functions to support this.
8. Message Passing: Objects communicate with one another by sending and receiving
information to each other. 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 results. Message passing involves specifying the name of the object, the name of
the function and the information to be sent.

More about Classes

1. Class name must start with an uppercase letter. If class name is made of more than one
word, then first letter of each word must be in uppercase. Example,class Study, class
employee etc.
2. Classes contain data members and member functions, and the access of these data
members and variable depends on the access specifiers (discussed in next section).
3. Class's member functions can be defined inside the class definition or outside the class
definition.
4. Class in C++ is similar to structures in C, the only difference being, class defaults to
private access control, whereas structure defaults to public.

Prof. Hemchandra Kumbhar Page 5


C++ with Object Oriented Programming

Procedure Oriented Programming Object Oriented Programming

Divided Into In POP, program is divided into small In OOP, program is divided into parts
parts called functions. called objects.
Importance In POP, Importance is not given In OOP, Importance is given to the
to data but to functions as well data rather than procedures or
as sequence of actions to be done. functions because it works as a real
world.
Approach POP follows Top Down approach. OOP follows Bottom Up approach.
Access POP does not have any OOP has access specifiers named
Specifiers accessspecifier. Public, Private, Protected, etc.
Data In POP, Data can move freely from In OOP, objects can move and
Moving function to function in the system. communicate with each other
through member functions.
Expansion To add new data and function in POP OOP provides an easy way to add
is not so easy. new data and function.
Data Access In POP, Most function uses Global In OOP, data cannot move easily from
data for sharing that can be accessed function to function, it can be kept
freely from function to function in public or private so we can control
the system. the access of data.
Data Hiding POP does not have any proper way OOP provides Data Hiding so
for hiding data so it is less secure. Provides more security.
Overloading In POP, Overloading is not possible. In OOP, overloading is possible in the
form of Function Overloading and
Operator Overloading.
Examples Example of POP are : C, VB, Example of OOP are : C++, JAVA,
FORTRAN, Pascal. VB.NET, C#.NET.

Prof. Hemchandra Kumbhar Page 6


C++ with Object Oriented Programming

UNIT II
1. Classes and Objects:
1.1. Simple classes (Class specification, class members accessing)
1.2. Defining member functions
1.3. Access Specifier
1.4. Passing object as an argument
1.5. Returning object from functions
1.6. Friend classes
1.7. Pointer to object
1.8. Array of pointer to object
2. Constructors and Destructors:
2.1. Introduction
2.2. Default Constructor
2.3. Parameterized Constructor
2.4. Copy Constructor
2.5. Destructors

1. Classes and Objects

1.1. Simple classes (Class specification, class members accessing):

The main purpose of C++ programming is to add object orientation to the C


programming language and classes are the central feature of C++ that supports object-
oriented programming and are often called user-defined types.

When we define any class, we are not defining any data, we just define a structure or a
blueprint, as to what the object of that class type will contain and what operations can be
performed on that object.

A class definition starts with the keyword class followed by the class name; and the
class body, enclosed by a pair of curly braces. A class definition must be followed either by
a semicolon or a list of declarations. For example, we defined the Box data type using the
keyword class as follows:

Class ClassName
{
Access specifier:
Data members;
Member Functions(){
Statements…
}
};

Prof. Hemchandra Kumbhar Page 7


C++ with Object Oriented Programming

Example1:

class Student
{
public:
int rollno;
char name[25];
};

Example2:

class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The keyword public determines the access attributes of the members of the class that
follow it. A public member can be accessed from outside the class anywhere within the
scope of the class object. You can also specify the members of a class
as private or protected which we will discuss in a sub-section.

Define C++ Objects:

A class provides the blueprints for objects, so basically an object is created from a
class. We declare objects of a class with exactly the same sort of declaration that we declare
variables of basic types.

Following statements declare two objects of class Box:

Box Box1; // Declare Box1 of type Box


Box Box2; // Declare Box2 of type Box
Box Box1, Box2;

Both of the objects Box1 and Box2 will have their own copy of data members.

Class ClassName
{
Access specifier:
Data members;
Member Functions(){
Statements…
}
};
void main ()
{
ClassName Obj1;
Obj1. Functions ();
}

Prof. Hemchandra Kumbhar Page 8


C++ with Object Oriented Programming

Example:
#include<iostream.h>

class car
{
public:
int number;

void start()
{
cout<<"Car Started...."<<endl;
}

void stop()
{
cout<<"Car Stop...."<<endl;
}
};

void main()
{
car c1;
cout<<"Enter car number"<<endl;
cin>>c1.number;
cout<<"Car Number="<<c1.number<<endl;
c1.start();
c1.stop();
}

1.2. Defining member functions

A member function of a class is a function that has its definition or its prototype within
the class definition like any other variable. It operates on any object of the class of which it
is a member, and has access to all the members of a class for that object.

class circle
{
private:
float radius;
public:
void getradius(); //Declare member function
void showarea(); //Declare member function
};

Member functions can be defined within the class definition or separately using scope
resolution operator (: :). Defining a member function within the class definition declares
the function inside the class as below-

Prof. Hemchandra Kumbhar Page 9


C++ with Object Oriented Programming

#include<iostream.h>
#define pi 3.1416
class circle
{
private:
float radius;
public:
void getradius()
{
cout<<"Enter the Radius:";
cin>>radius;
}
void showarea()
{
cout<<"Area="<<pi*radius*radius<<endl;
}
};
void main()
{
circle x;
x.getradius();
x.showarea();
}
If you like, you can define the same function outside the class using the scope resolution
operator (::) as follows −

#include<iostream.h>
#define pi 3.1416
class circle
{
private:
float radius;
public:
void getradius();
void showarea();
};
void circle::getradius()
{
cout<<"Enter the Radius:";
cin>>radius;
}
void circle::showarea()
{
cout<<"Area="<<pi*radius*radius<<endl;
}
void main()
{circle x;
x.getradius();
x.showarea();
}

Prof. Hemchandra Kumbhar Page 10


C++ with Object Oriented Programming

1.3. Access Specifier

Access modifiers are used to implement important feature of Object Oriented


Programming known as Data Hiding. Access modifiers or Access Specifiers in a class are
used to set the accessibility of the class members. That is, it sets some restrictions on the
class members not to get directly accessed by the outside functions. If we do not specify
any access modifiers for the members inside the class then by default the access modifier
for the members will be Private.

There are 3 types of access modifiers available in C++:

1. Public
2. Private
3. Protected

1. Public: The public members of a class can be accessed from anywhere in the
program using the direct member access operator (.) with the object of that class.

Example
#include<iostream.h>

// class definition
class Circle
{
public:
double radius;
double area()
{
return 3.14*radius*radius;
}
};

void main()
{
Circle obj;
obj.radius = 5.5;
cout<< "Radius is:" <<obj.radius<< "\n";
cout<< "Area is:" <<obj.area()<<endl;
}

2. Private: The class members declared as private can be accessed only by the
functions inside the class. They are not allowed to be accessed directly by any
object or function outside the class. Only the member functions or the friend
functions are allowed to access the private data members of a class. Private is
default access Specifierin a class. A program can access the private members of a
class only by using the public member functions of the class. This insulation of data
members from directaccess in a program is called information hiding.

Prof. Hemchandra Kumbhar Page 11


C++ with Object Oriented Programming

Example:

#include<iostream.h>
class Circle
{
private:
double radius; // private data member
public:
double area() // public member function
{
return 3.14*radius*radius; // function can access privatedata member radius
}
};

void main()
{
Circle obj; // creating object of the class
obj.radius = 1.5; // trying to access private data member directly outside the class
cout<< "Area is:" <<obj.area();
}

However, we can access the private data members of a class indirectly using the public
member functions of the class.

3. Protected: Protected access modifier is similar to that of private access modifiers,


the difference is that the class member declared as Protected are inaccessible
outside the class but they can be accessed by any subclass (derived class) of that
class.

Example

#include<iostream.h>
classBaseCircle
{
protected:
double radius; // protected data member
public:
void getradius()
{
cin>>radius;
}
};
classDerivedCircle:publicBaseCircle
{
public:
double area()
{
return 3.14*radius*radius;
// member function can access protected data member radius
}
};
Prof. Hemchandra Kumbhar Page 12
C++ with Object Oriented Programming

void main()
{
DerivedCircleobj;
cout<<"Enter Radius"<<endl;
// trying to access protecteddata memberdirectly outside the class
obj.getradius();
cout<< "Area is:" <<obj.area()<<endl;
}

1.4. Passing object as an argument

1. The objects of a class can be passed as arguments to member functions as well as


nonmember functions either by value or by reference.
2. When an object is passed by value, a copy of the actual object is created inside the
function.
3. This copy is destroyed when the function terminates.
4. This is useful, when we want to initialize all data members of an object with another
object, we can pass objects and assign the values of supplied object to the current
object.
5. Moreover, any changes made to the copy of the object inside the function are not
reflected in the actual object.
6. On the other hand, in pass by reference, only a reference to that object (not the entire
object) is passed to the function. Thus, the changes made to the object within the
function are also reflected in the actual object.

Example1:

#include<iostream.h>
#define pi 3.1416
class circle
{
private:
float radius;
public:
void setradius(float z)
{
radius=z;
}
void showarea(circle c1)
{
cout<<"Area="<<pi*c1.radius*c1.radius<<endl;
}
};

void main()
{
circlex,y;
x.setradius(10);
y.showarea(x);
}
Prof. Hemchandra Kumbhar Page 13
C++ with Object Oriented Programming

Example2:
#include<iostream.h>
class Circle
{
public:
double radius;
Circle()
{
radius=10;
}

intdisplay(Circle &x)
// intdisplay(Circle x)
{
returnx.radius++;
}
};

void main()
{
Circle obj1;
cout<< "Radius is:" <<obj1.radius<<endl;
cout<< "Radius is:" <<obj1.display(obj1)<<endl;
cout<< "Radius is:" <<obj1.radius<<endl;
}

1.5. Returning object from functions

A function can also return objects either by value or by reference. When an object is
returned by value from a function, a temporary object is created within the function,
which holds the return value. This value is further assigned to another object in the calling
function.
The syntax for defining a function that returns an object by value is
class_namefunction_name (parameter_list)
{
// body of the function
return objectname;
}
To understand the concept of returning an object by value from a function, consider
this example.
Example

#include<iostream.h>
#define pi 3.1416
class circle
{
public:
floatradius,area;
void setradius(float z)

Prof. Hemchandra Kumbhar Page 14


C++ with Object Oriented Programming

{
radius=z;
}
circlecalcarea()
{
circle c1;
c1.area=pi*radius*radius;
return c1;
}
void showarea()
{
cout<<"Area="<<area<<endl;
}
};

void main()
{
circlex,y;
x.setradius(10);
y=x.calcarea();
y.showarea();
}

1.6. Friend classes

A friend class can access private and protected members of other class in which it is
declared as friend. It is sometimes useful to allow a particular class to access private
members of other class.Following are some important points about friend functions
and classes:
a) Friends should be used only for limited purpose. too many functions or external
classes are declared as friends of a class with protected or private data,
b) Itreduced the value of encapsulation of separate classes in object-oriented
programming.
c) Friendship is not mutual. If a class A is friend of B, then B doesn’t become friend of
A automatically.
d) Friendship is not inherited.
e) Friend functions do not have a ‘this’ pointer, because friends are not members of a
class.
f) The concept of friends is not there in Java.

Example:

#include<iostream.h>
class Circle
{
// private data member
private:
double radius;

Prof. Hemchandra Kumbhar Page 15


C++ with Object Oriented Programming

public:
friend void showarea();
Circle()
{
radius=10;
}
};
void showarea()
{
Circle x;
cout<<"Area="<<3.14*x.radius*x.radius<<endl;
}
void main()
{
Circle obj;
showarea();
}

1.7. Pointer to object

We can define pointer of class type, which can be used to point to class objects. Just like
other pointers, the object pointers are declared by placing * in front of a object pointer's
name. When accessing members of a class using an object pointer, the arrow operator (->)
is used instead of dot operator. It takes the following general form:

class-name ∗ object-pointer;

Example:

#include<iostream.h>
class Circle
{
public:
double radius;
double area()
{
return 3.14*radius*radius;
}
};

void main()
{
Circle obj,*ptr;
ptr=&obj;
// accessing public datamember outside class
obj.radius = 5.5;
cout<< "Radius is:" <<ptr->radius << "\n";
cout<< "Area is:" <<ptr->area()<<endl;
cout<< "Area is:" << (*ptr).area()<<endl;

Prof. Hemchandra Kumbhar Page 16


C++ with Object Oriented Programming

1.8. Array of pointer to object


A pointer is a variable whose value is the address of another variable.

#include<iostream.h>
class Circle
{
public:
double radius[5];
};

void main()
{
inti;
Circle obj[5],*ptr[5];

for(i=0;i<=4;i++)
ptr[i]=&obj[i];

for(i=0;i<=4;i++)
cin>>ptr[i]->radius[i];

for(i=0;i<=4;i++)
cout<< "Radius is:" <<ptr[i]->radius[i] << "\n";
}

2. Constructors and Destructors:

2.1. Introduction
a) A class constructor is a special member function of a class that is executed whenever
we create new objects of that class.
b) A constructor will have exact same name as the class
c) It does not have any return type at all, not even void.
d) Constructors can be very useful for setting initial values for certain member variables.
e) Constructors can be defined either inside the class definition or outside class
definition using class name and scope resolution (: :)operator.
f) Default, Parameterized and Copy Constructors are types of Constructors

2.2. Default Constructor

Default constructor is the constructor which doesn't take any argument. It has no
parameter. Default Constructor is also called as Empty Constructor which has no arguments

Syntax:
class_name ()
{
Prof. Hemchandra Kumbhar Page 17
C++ with Object Oriented Programming

Constructor Definition
}
Example:

#include<iostream.h>
class Circle
{
public:
double radius;
Circle()
{
radius=10;
}
};
void main()
{
Circle obj;
cout<< "Radius is:" <<obj.radius<<endl;
}

In this case, as soon as the object is created the constructor is called which initializes its
data members. A default constructor is so important for initialization of object members,
that even if we do not define a constructor explicitly, the compiler will provide a default
constructor implicitly.

2.3. Parameterized Constructor

These are the constructors with parameter. Using this Constructor, you can provide
different values to data members of different objects, by passing the appropriate values as
argument.

Example:
#include<iostream.h>
class Circle
{
public:
double radius;
Circle()
{
radius=10;
}
Circle(int i)// Parameterized Constructor
{
radius=i;
}
};
void main()
{
Circle obj1,obj2(20);
cout<< "Radius is:" <<obj1.radius<<endl;

Prof. Hemchandra Kumbhar Page 18


C++ with Object Oriented Programming

cout<< "Radius is:" <<obj2.radius<<endl;


}
2.4. Copy Constructor

These are special type of Constructors which takes an object as argument, and is used to
copy values of data members of one object into other object.

Example:
#include<iostream.h>
class Circle
{
public:
double radius;
Circle()
{
radius=10;
}
Circle(int i)
{
radius=i;
}
};

void main()
{
Circle obj1 (20), obj2;
cout<< "Radius is:" <<obj1.radius<<endl;
cout<< "Radius is:" <<obj2.radius<<endl;
obj2=obj1;
cout<< "Radius is:" <<obj2.radius<<endl;
}
2.5. Destructors

a) Destructor is a special class function which destroys the object as soon as the
scope of object ends.
b) Destructor free up the Memory which is Allocated by Constructor
c) The destructor is called automatically by the compiler when the object goes out of
scope.
d) The syntax for destructor is same as that for the constructor, the class name is
used for the name of destructor, with a tilde ~ sign as prefix to it.

Syntax:

~ class_name ()
{
DestructorsDefinition
}

Prof. Hemchandra Kumbhar Page 19


C++ with Object Oriented Programming

Example:

#include <iostream.h>
class display
{
public:
display()
{
cout<< "\nCreateObject::" <<endl;
}
~display()
{
cout<< "\nDestroyedObject::" <<endl;
}
};

void main()
{
display x;
}

Prof. Hemchandra Kumbhar Page 20


C++ with Object Oriented Programming

UNIT III
1. Polymorphism:
1.1. Concept of function overloading
1.2. Overloaded operators
1.3. Overloading unary and binary operators
1.4. Overloading comparison operator
1.5. Overloading arithmetic assignment operator
1.6. Data Conversion between objects and basic types
1.7. Constructor Overloading
2. Virtual Functions:
2.1. Introduction and need
2.2. Pure Virtual Functions
2.3. Abstract classes
2.4. Virtual destructors
2.5. Static Functions
2.6. this Pointer

1. Polymorphism:

1.1. Concept of function overloading

If any classes have multiple functions with same names but different parameters, then
they are said to be overloaded. Function overloading allows you to use the same functions
name for to perform, either same or different functions(task) in the same class. You can
have multiple definitions for the same function name in the same scope. You cannot
overload function declarations that differ only by return type.

Function overloading is usually used to enhance the readability of the program. If you
have to perform one single operation but with different number or types of arguments,
then you can simply overload the function.

Ways to overload a function


1. By changing number of Arguments.
2. By having different data types of argument.

1. Number of Arguments different

In this type of function overloading we define two functions with same names but
different number of parameters of the same type. For example, in the below mentioned
program we have made two sum() functions to display sum of two and three integers.

Prof. Hemchandra Kumbhar Page 21


C++ with Object Oriented Programming

Example:

#include<iostream.h>
class calc{
public:
void sum(int x, int y)
{
cout<<x+y<<endl;
}
void sum(int x, int y, int z)
{
cout<<x+y+z<<endl;
}
};
void main()
{
calc c1;
c1.sum(10,20);
c1.sum(10,20,30);
}
Here sum() function is overloaded, to have two and three arguments. Which sum()
function will be called, depends on the number of arguments.

2. Different Data type of Arguments

In this type of overloading we define two or more functions with same name and same
number of parameters, but the type of parameter is different. For example in this
program, we have two sum() function, first one gets two integer arguments and second
one gets two double arguments.
Example:

#include<iostream.h>
class demo{
public:
void calc(int x, int y)
{
cout<<x*y<<endl;;
}
void calc(double x,double y)
{
cout<<x*y<<endl;
}
};
void main()
{
demo c1;
c1.calc(12,11);
c1.calc(10.5,20.3);
}

Prof. Hemchandra Kumbhar Page 22


C++ with Object Oriented Programming

 Default Arguments
When we mention a default value for a parameter while declaring the function, it is said
to be as default argument. In this case, even if we make a call to the function without
passing any value for that parameter, the function will take the default value specified.
Example:

#include<iostream.h>
class calc{
public:
void sum(intx,int y=5)
{
cout<<x+y<<endl;
}
void sum(double x,double y)
{
cout<<x+y<<endl;
}
};
void main()
{
calc c1;
c1.sum(12);
c1.sum(10.5,20.3);
}

1.2. Overloaded operators

Operator overloading is an important concept in C++. It is a type of polymorphism in


which an operator is overloaded to give user defined meaning to it. Overloaded operator
is used to perform operation on user-defined data type. For example, '+' operator can be
overloaded to perform addition on various data types, like for Integer,
String(concatenation) etc.
Almost any operator can be overloaded in C++. However, there are few operators which
cannot be overloaded. Operators that are not overloaded are follows
 scope operator (: :)
 sizeof()
 member selector –(.)
 member pointer selector - *
 ternary operator -?:

Prof. Hemchandra Kumbhar Page 23


C++ with Object Oriented Programming

Operator Overloading Syntax

Implementing Operator Overloading


Operator overloading can be done by implementing a function which can be:

1. Member Function
2. Non-Member Function
3. Friend Function

Operator overloading function can be a member function if the Left operand is an Object
of that class, but if the Left operand is different, then Operator overloading function must
be a non-member function.
Operator overloading function can be made friend function if it needs access to the
private and protected members of class.

1.3. Overloading unary and binary operators

The unary operators operate on a single operand and following are the examples of
Unary operators −
 The increment (++) and decrement (--) operators.
 The unary minus (-) operator.
 The logical not (!) operator.

 Unary Operator Overloading (++, --, -,+,! )

The unary operators operate on the object for which they were called and normally, this
operator appears on the left side of the object, as in !obj, -obj, and ++obj but sometime
they can be used as postfix as well like obj++ or obj--.

Example1:

#include<iostream.h>
#include<conio.h>
class Circle
{
public:
int r;

Prof. Hemchandra Kumbhar Page 24


C++ with Object Oriented Programming

void operator ++()


{
r++;
//use r=-r for ‘-obj’ operator
}
};
void main()
{
Circle obj;
cout<<"Enter the Radius:"<<endl;
cin>>obj.r;
cout<<"Objects original Radius:";
cout<<obj.r<<endl;
obj++;
cout<<"After incrementing"<<endl;
cout<<"Objects changed Radius:";
cout<<obj.r<<endl;
}

Example2 :

#include<iostream.h>
#include<conio.h>
class Circle
{
public:
int r;
Circle()
{
r=0; //used as true or false
}
void operator !()
{
r=!r;
}
};
void main()
{
Circle obj;
cout<<"Objects original Radius:";
cout<<obj.r<<endl;
!obj;
cout<<"After change"<<endl;

Prof. Hemchandra Kumbhar Page 25


C++ with Object Oriented Programming

cout<<"Objects changed Radius:";


cout<<obj.r<<endl;
}

Binary Operator Overloading (Arithmetic Operator Overloading +, -, /, *)

The binary operators take two arguments (i.e. two objects). You use binary operators
very frequently like addition (+) operator, subtraction (-) operator and division (/)
operator.
Following example explains how addition (+) operator can be overloaded. Similar way,
you can overload subtraction (-) and division (/) operators.

Example 1:
#include<iostream.h>
#include<conio.h>
class Circle
{
public:
int r;
Circle()
{
r=0;
}
Circle(int x)
{
r=x;
}
Circle operator +(Circle X)
{
Circle temp;
temp.r=r+X.r;
return temp;
}
};
void main()
{
Circle C1(10), C2(20), C3;
C3=C1+C2;
cout<<"C3 Radius:"<<C3.r<<endl;
}

Prof. Hemchandra Kumbhar Page 26


C++ with Object Oriented Programming

 Assignment Operator Overloading (=):

Assignment Operator is used to assign value to a variable. Assignment operator is


denoted by equal to sign. Assignment operator has two values L-Value and R-value.
Operator copies R-Value into L-Value. It is a binary operator. By overloading assignment
operator, all values of one object (i.e. instance variables) can be copied to another object.
Assignment operator must be overloaded by a non-static member function only. If the
overloading function for the assignment operator is not written in the class, the compiler
generates the function to overload the assignment operator.
Example:
#include<iostream.h>
#include<conio.h>
class Circle
{
public:
int r;
Circle()
{
r=0;
}
Circle(int x)
{
r=x;
}
void operator = (Circle x)
{
r=x.r;
}
};
void main()
{
Circle C1(10), C2;
C2=C1;
cout<<"C2 Radius:"<<C2.r<<endl;
}

1.4. Overloading comparison operator (Relational operator overloading)

There are various relational operators supported by C++ language like (<, >, <=, >=, ==,
etc.) which can be used to compare C++ built-in data types. You can overload any of these
operators, which can be used to compare the objects of a class. Following example
explains how a < operator can be overloaded and similar way you can overload other
relational operators.

Prof. Hemchandra Kumbhar Page 27


C++ with Object Oriented Programming

Example1:
#include<iostream.h>
#include<conio.h>
class Circle
{
public:
int r;
Circle(int x)
{
r=x;
}
bool operator <(Circle C3)
{
if(r<C3.r)
{
return true;
}
else
{
return false;
}
}
};
void main()
{
Circle C1(10), C2(20);
if(C1<C2 )
cout<< "C1 is less than C2 " <<endl;
else
cout<< "C2 is less than C1 " <<endl;
}

1.5. Overloading arithmetic assignment (Compound)operator (+=, -=, /=, *=, %=)

There are arithmetic assignment operators corresponding to all the arithmetic opera-
tions: +=, -=, *=, /=, and %= (and some other operators as well). The following example
shows the arithmetic assignment operators in use:
Example:
#include<iostream.h>
#include<conio.h>
class Circle
{

Prof. Hemchandra Kumbhar Page 28


C++ with Object Oriented Programming

public:
int r;
Circle()
{
r=0;
}
Circle(int x)
{
r=x;
}
void operator +=(Circle x)
{
r+=x.r;
}
};
void main()
{
Circle C1(10), C2(5), C3;
C2+=C1;
cout<<"C2 Radius:"<<C2.r<<endl;
}

1.6. Data Conversion between objects and basic types

The C++ compiler automatically handles the type conversion in an expression


involving operands of built in data type, but compiler cannot handle the type conversion
in the expression involving user-defined data types such as classes. This is because the
operator is overloaded explicitly by the user to handle user-defined data types. Thus, the
user has to provide the conversion mechanisms to handle the type conversion for the
user-defined data types.

There can be three types of type conversion in an expression involving user-defined


data types. These are
 Basic type to class type (User-defined)
 Class type to Basic type
 One class type to another class type.

1. Basic type to class type (User-defined)

The conversion of a basic data type to class type is possible by defining a constructor of
the class that accepts an argument of any object type, which is converted to class type.
The object of class type that calls the constructor is passed implicitly.

Example:

Prof. Hemchandra Kumbhar Page 29


C++ with Object Oriented Programming

#include<iostream.h>
#include<conio.h>
classabc
{
int n;
public:
abc(int x)
{
n=x;
}
void show ()
{
cout<<"\nValue="<<n;
}
};
void main()
{
abc a=10;
//abc a(10);
cout<<"object's data:";
a.show();
getch();
}

2. Class type (User-Defined) to Basic type

In this case, the constructor cannot be used as it requires a class object on the left hand
side of the type conversion. To handle such conversions, an overloaded casting operator
function must be defined. The conversion function must be non-static member function of
the class and cannot have an argument list or return type. Conversion function can be
called explicitly like a constructor.

Example:
#include<iostream.h>
#include<conio.h>
classabc
{
int a;
public:
abc(int x)
{
a=x;
}
void show()
{
cout<<"\nA="<<a;
}
operatorint()
{

Prof. Hemchandra Kumbhar Page 30


C++ with Object Oriented Programming

return a;
}
};

void main()
{
abc a=10;
int n;
cout<<"\n object's data:";
a.show();
cout<<"\n after conversion:";
n=a;
cout<<"\n A="<<n;
getch();
}

3. One class type (User-Defined) to another class type (User-Defined)

When one class type is to be converted into another class type, the class type
(object)that appeared on the right hand side is known as source class and the class
type (object) that appears on left hand side is known as the destination class. This type
of conversion can be handled by using either the constructor or the conversion
function.

Example:
#include<iostream.h>
#include<conio.h>
class Circle
{
public:
int r;
Circle()
{
r=0;
}
Circle(int x)
{
r=x;
}
void operator =(Circle x)
{
r=x.r;
}
};

void main()

Prof. Hemchandra Kumbhar Page 31


C++ with Object Oriented Programming

{
Circle C1(10),C2;
C2=C1;
cout<<"C2 Radius:"<<C2.r<<endl;
}

Prof. Hemchandra Kumbhar Page 32


C++ with Object Oriented Programming

1.7. Constructor Overloading

In C++, we can have more than one constructor in a class with same name, as long as
each has a different list of arguments. This concept is known as Constructor Overloading
and is quite similar to function overloading.

1. Overloaded constructors essentially have the same name (name of the class) and
different number of arguments.
2. A constructor is called depending upon the number and type of arguments passed
from objects.
3. While creating the object, arguments must be passed to let compiler know, which
constructor needs to be called.

Example:

#include <iostream.h>
class Circle
{
public:
float radius;
Circle() // Constructor with no parameters
{
radius = 0;
}

Circle(float r1, float r2) // Constructor with two parameters


{
radius = r1+r2;
}

void display()
{
cout<<radius<<endl;
}
};

void main()
{
Circle c1,c2( 10.5, 20.4);
c1.display();
c2.display();
}

Prof. Hemchandra Kumbhar Page 33


C++ with Object Oriented Programming

2. Virtual Functions:
2.1. Introduction and need

A virtual function a member function which is declared within base class and is re-defined
(Overridden) by derived class. When you refer to a derived class object using a pointer or a
reference to the base class, you can call a virtual function for that object and execute the
derived class’s version of the function.
 They are mainly used to achieve Runtime polymorphism
 Functions are declared with a virtual keyword in base class.

Virtual function is needed to implement different functionalities in different derived


classes of a base class. We need virtual function to make true concept of function overriding.
If we want to make same function for multiple purposes, then we use concept of overriding.

Rules for Virtual Functions

 They must be declared in public section of class.


 Virtual functions cannot be static and cannot be a friend function of another class.
 Virtual functions should be accessed using pointer or reference of base class type to
achieve run time polymorphism.
 The prototype of virtual functions should be same in base as well as derived class.
 They are always defined in base class and overridden in derived class. It is not
mandatory for derived class to override (or re-define the virtual function), in that case
base class version of function is used.
 A class may have virtual destructor but it cannot have a virtual constructor.

Example:

#include<iostream.h>
class base
{
public:
virtual void print ()
{
cout<< "print base class" <<endl;
}
void show ()
{
cout<< "show base class" <<endl;
}
};

Prof. Hemchandra Kumbhar Page 34


C++ with Object Oriented Programming

Classderived:public base
{
public:
void print ()
{
cout<< "print derived class" <<endl;
}
void show ()
{
cout<< "show derived class" <<endl;
}
};
void main()
{
base *bptr;
derived d;
bptr = &d;
bptr->print(); //virtual function, binded at runtime
bptr->show(); // Non-virtual function, binded at compile time
}

2.2. Pure Virtual Functions and Abstract classes

a) Pure Virtual Functions

Sometimes implementation of all function cannot be provided in a base class because we


don’t know the implementation. A pure virtual function (or abstract function) in C++ is
a virtual function for which we don’t have implementation, we only declare it.

1. Pure virtual Functions are virtual functions with no definition.


2. They start with virtual keyword and ends with = 0. i.e. A pure virtual function is
declared by assigning 0 in declaration.
3. Here is the syntax for a pure virtual function, virtual void functionname() = 0;
4. Pure Virtual functions can be given a small definition in the Abstract class Still you
cannot create object of Abstract class.
5. The Pure Virtual function must be defined outside the class definition.
6. If you will define it inside the class definition, complier will give an error.
7. Inline pure virtual definition is Illegal.

Syntax:

classClassname{

public: // Data members of class


virtual void functionname() = 0; // Pure Virtual Function
/* Other members */
};

Prof. Hemchandra Kumbhar Page 35


C++ with Object Oriented Programming

b) Abstract Class:

1. Abstract Class is a class which contains at least one Pure Virtual function in it.
2. Abstract classes are used to provide an Interface for its sub classes.
3. Abstract class cannot be instantiated (not create as an object), but pointers and
references of Abstract class type can be created.
4. Abstract class can have normal functions and variables along with a pure virtual
function.
5. Abstract classes are mainly used for Up casting, so that its derived classes can use its
interface.
Example for Pure Virtual Functions and Abstract classes

#include<iostream.h>
class Base //Abstract base class
{
public:
virtual void show() = 0; //Pure Virtual Function
};
classDerived:public Base
{
public:
void show()
{
cout<< "Implementation of Virtual Function in Derived class\n";
}
};

void main()
{
//Base obj; //Compile Time Error
Base *b;
Derived d;
b = &d;
b->show();
}

2.3. Virtual Destructors

Destructors in the Base class can be Virtual. Whenever Upcasting is done, Destructors
of the Base class must be made virtual for proper destruction of the object when the
program exits. Constructors are never Virtual, only Destructors can be Virtual.

Prof. Hemchandra Kumbhar Page 36


C++ with Object Oriented Programming

Example:

#include<iostream.h>
class Base
{
public:
Base(){
cout<<"Constructor in Base"<<endl;
}

//~Base(){ // this is a destructor:

virtual ~Base(){
cout<<"Destructor in Base"<<endl;
}
};

class Derive: public Base


{
public:
Derive(){
cout<<"Constructing Derive"<<endl;
}
~Derive(){
cout<<"Destroying Derive"<<endl;
}
};

void main()
{
Base *basePtr = new Derive();
deletebasePtr;
}

2.4. Static Functions

1. By declaring a function member as static, you make it independent of any particular


object of the class.
2. A static member function can be called even if no objects of the class exist
3. It can be called using an object and the direct member access ‘.’ operator. But, its more
typical to call a static member function by itself, using class name and scope
resolution-:: operator.
4. A static member function can only access static data member, other static member
functions and any other functions from outside the class.
5. Static member functions have a class scope and they do not have access to the ‘this’
pointer of the class.

Prof. Hemchandra Kumbhar Page 37


C++ with Object Oriented Programming

Example:

#include<iostream.h>
class Circle
{
public:
staticint Radius;
static void show()
{
cout<<"Radius="<<Radius<<endl;
}

};
intCircle::Radius=15;
void main()
{
Circle c;
cout<<c.Radius<<endl;
c.show();
Circle::show();
}

2.5. this Pointer

Every object in C++ has access to its own address through an pointer is called as
‘this’ pointer. The ‘this’ pointer is an implicit parameter to all member functions.
Therefore, inside a member function, this may be used to refer to the invoking object.
Friend functions do not have a ‘this’ pointer, because friends are not members of a
class. Only member functions have a ‘this’ pointer. Static member functions do not
have access to the ‘this’ pointer of the class.

Example:
#include <iostream.h>
classMyClass {
int i;
public:
void setI(intval)
{
this->i = val;
}
intgetI() {
return this->i;
}
};
void main()
{
MyClassobj;
obj.setI(100);
cout<<obj.getI();

Prof. Hemchandra Kumbhar Page 38


C++ with Object Oriented Programming

}
UNIT IV
1. Program development using Inheritance:
1.1. Introduction
1.2. Understanding inheritance
1.3. Advantages provided by inheritance
1.4. Choosing the access specifier & Derived class declaration
1.5. Derived class constructors
1.6. Types of inheritance
1.7. Containership
2. Exception Handling:
2.1. Introduction
2.2. Exception Handling Mechanism
2.3. Concept of throw & catch with example

1. Program development using Inheritance:

1.1. Introduction

Reusability is one of the important characteristics of Object Oriented Programming


(OOP). Instead of trying to write programs repeatedly, using existing code is a good
practice for the programmer to reduce development time and avoid mistakes. In C++,
reusability is possible by using Inheritance.

1.2. Understanding inheritance

Inheritance is one of the key features of Object-oriented programming in C++. It allows


user to create a new class (derived class) from an existing class (base class). The technique
of deriving a new class from an old one is called inheritance. The old class is referred to as
base class and the new class is referred to as derived class or subclass.

Basic Syntax of Inheritance


Class Subclass_name :access_mode Superclass_name

Or Class Deriveclass_name :access_mode Baseclass_name

While defining a subclass like this, the super class must be already defined or at least
declared before the subclass declaration.
Access Mode is used to specify, the mode in which the properties of super class will be
inherited into subclass as public, private or protected.
1.3. Advantages provided by inheritance

Inheritance allows us to define a class in terms of another class, which makes it easier to
create and maintain an application. This also provides an opportunity to reuse the code

Prof. Hemchandra Kumbhar Page 39


C++ with Object Oriented Programming

functionality and fast implementation time. Inheritance makes the code reusable. When
we inherit an existing class, all its methods and fields become available in the new class,
hence code is reused. This makes your code cleaner, understandable and extendable.
1.4. Choosing the access specifier and Derived class declaration
You can declare a derived class from a base class with different access control, i.e.,
public inheritance, protected inheritance or private inheritance.

#include <iostream.h>
class base
{
.... ... ....
};
class derived :access_specifier baseclassname
{
.... ... ....
};

Public, protected or private keyword is used in place of access_ specifier term used in the
above code.
We hardly use protected or private inheritance, but public inheritance is commonly
used. While using different type of inheritance, following rules are applied −

1. Public Inheritance − When deriving a class from a public base class, public members
of the base class become public members of the derived class and protected members
of the base class become protected members of the derived class. A base class's private
members are never accessible directly from a derived class, but can be accessed
through calls to the public and protected members of the base class.
2. Protected Inheritance − When deriving from a protected base
class, public and protected members of the base class become protected members of
the derived class.
3. Private Inheritance − When deriving from a private base
class, public and protected members of the base class become private members of the
derived class.

Syntax:
class base
{
public: int x;
protected: int y;
private: int z;
};
Class public Derived: public base
{
// x is public

Prof. Hemchandra Kumbhar Page 40


C++ with Object Oriented Programming

// y is protected
// z is not accessible from public Derived
};
ClassprotectedDerived: protected base
{
// x is protected
// y is protected
// z is not accessible from protectedDerived
};

classprivateDerived: private base


{
// x is private
// y is private
// z is not accessible from privateDerived
}
We can summarize the different access types according to - who can access them in the
following way −

Access public protected private

Same class yes yes yes

Derived classes yes yes no

Outside classes yes no no

1.5. Derived class constructors

Base class constructors are always called in the derived class constructors. Whenever
you create derived class object, first the base class default constructor is executed and
then the derived class's constructor finishes execution.

Multiple Inheritances is a feature of C++ where a class can inherit from more than one
classes. The constructors of inherited classes are called in the same order in which they
are inherited. For example, in the following program, B’s constructor is called before A’s
constructor.
Example:
#include<iostream.h>
class A
{
public:
A()
{

Prof. Hemchandra Kumbhar Page 41


C++ with Object Oriented Programming

cout<< "A's constructor called" <<endl;


}
};
class B
{
public:
B() { cout<< "B's constructor called" <<endl; }
};

class C: public B, public A // Note the order


{
public:
C() { cout<< "C's constructor called" <<endl; }
};

void main()
{
C c;
}

1.6. Types of Inheritance

In C++, we have 5 different types of Inheritance. Namely,

1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance (also known as Virtual Inheritance)

1. Single Inheritance: In this type of inheritance one derived class inherits from only
one base class. It is the simplest form of Inheritance.

Example:

#include<iostream.h>
class Circle{
public:
float radius;
Prof. Hemchandra Kumbhar Page 42
C++ with Object Oriented Programming

void getradius()
{
cout<<"Enter Radius"<<endl;
cin>>radius;
}
};

class Carea:public Circle


{
public:
float area;
void showarea()
{
area=3.1416*radius*radius;
cout<<"Area="<<area<<endl;
}
};

void main()
{
Carea c1;
c1.getradius();
c1.showarea();
}

2. Multiple Inheritances: In this type of inheritance a single derived class may


inherit from two or more than two base classes.

Example:

#include<iostream.h>
class Rlength{
public:
int l;
void getlength()
{
cout<<"Enter Length"<<endl;
cin>>l;

Prof. Hemchandra Kumbhar Page 43


C++ with Object Oriented Programming

}
};

class Rbreadth{
public:
int b;
void getbreadth()
{
cout<<"Enter Breadth"<<endl;
cin>>b;
}
};

class Rectange:public Rlength,public Rbreadth


{
public:
float area;
void showarea()
{
area=2*(l+b);
cout<<"Area="<<area<<endl;
}
};
void main()
{
Rectange Obj;
Obj.getbreadth();
Obj.getlength();
Obj.showarea();
}

3. Hierarchical Inheritance: In this type of inheritance, multiple derived classes


inherits from a single base class.

Example:

#include<iostream.h>
class shape{
public:
int radius,l,b;

Prof. Hemchandra Kumbhar Page 44


C++ with Object Oriented Programming

void carea()
{
cout<<"Area="<<3.1416*radius*radius<<endl;
}
void rarea()
{
cout<<"Area="<<2*(l+b)<<endl;
}
};

class Circle:public shape


{
public:
void getradius()
{
cout<<"Enter Radius"<<endl;
cin>>radius;
}
};

class Rectange:public shape


{
public:
void getlb()
{
cout<<"Enter length and breadth"<<endl;
cin>>l>>b;
}
};

void main()
{
Circle c1;
Rectange r1;
c1.getradius();
c1.carea();
r1.getlb();
r1.rarea();
}

4. Multilevel Inheritance: In C++ programming, not only you can derive a class from
the base class but you can also derive a class from the derived class. This form of
inheritance is known as multilevel inheritance.
Class A {
….
};
Class B:public A {
……
};
Class C: public B
Prof. Hemchandra Kumbhar Page 45
C++ with Object Oriented Programming

{
…..
};

Example:

#include<iostream.h>
class A{
public:
void Display()
{
cout<<"A Class Content."<<endl;

}
};

class B: public A
{
public:
void Displayagain()
{
cout<<"B Class Content."<<endl;
}
};

class C:public B
{
public:
C()
{
cout<<"C Class Content."<<endl;
}
};

void main()
{
C obj;
obj.Display();
obj.Displayagain();

Prof. Hemchandra Kumbhar Page 46


C++ with Object Oriented Programming

}
5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is combination of Hierarchical
and Mutilevel Inheritance.

Example:

#include<iostream.h>
class A{
public:
int a;
void geta()
{
cout<<"Enter value of A"<<endl;
cin>>a;

}
};

class B: public A
{
public:
int b;
void getb()
{
geta();
cout<<"Enter value of B"<<endl;
cin>>b;
}
};

class C
{
public:
int c;
void getc()
{
cout<<"Enter value of C"<<endl;
cin>>c;
}
};

Prof. Hemchandra Kumbhar Page 47


C++ with Object Oriented Programming

class D:public B, public C


{
public:
void sum()
{
getb();
getc();
cout<<"Sum="<<a+b+c<<endl;
}
};

void main()
{
D obj;
obj.sum();
}

1.7. Containership

When a class contains objects of another class or its members, this kind of relationship is
class containership or nesting and the class, which contains object of another class as its
members, is class as container class.

Syntax for the declaration of another class is


Class classname1
{

….
};

Class classname2
{
….
….
};

Class classname3
{
Classname1 obj1;
Classname2 obj2;


};

Prof. Hemchandra Kumbhar Page 48


C++ with Object Oriented Programming

2. Exception Handling, Mechanism and Examples

An Exception is unexpected event that occurs during the exception of program and
alert normal flow of the program or terminate the program. 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.

 try − A try block identifies a block of code for which particular exceptions will be
activated. A set of statements that needs to be monitored for the exception is
contained in the try block. It's followed by one or more catch blocks. Whenever an
exception occurs within try block, it is thrown using the throw statement. These pass
the control to the catch block, which handles the exception appropriately.
 throw − A program throws an exception when a problem shows up. This is done using
a throw keyword.
 catch − The Catch block is also called as an exception handler and it must immediately
follow the try block that thrown exception. The catch keyword indicates the catching
of an exception.

syntax is:

try{
Statements……
.
throw exception;
}
catch(datatype parameter)
{
Statements…
}

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.

Example 1:
#include<iostream.h>
#include<conio.h>
void main()
{
int n;
cout<<”enter the number”<<endl;
cin>>n;
try{
if(n<0 || n>100)
throw (n);

Prof. Hemchandra Kumbhar Page 49


C++ with Object Oriented Programming

else
cout<<”your percentage:”<<n<<endl;
}catch( int i)
{
cout<<”invalid percentage…”<<endl;
}
}

Example 2:
#include<iostream.h>
void main()
{
top:
int n;
cout<<"Please Enter the Even number"<<endl;
cin>>n;
try{
if((n%2)==0)
cout<<"Well Done..."<<endl;
else
throw(n);
}catch(int a)
{
cout<<"Entered Number is odd Try again.."<<endl;
goto top;
}
}
Example 3:
#include<iostream.h>
void main()
{
int n1,n2,ans;
cout<<"enter the number1"<<endl;
cin>>n1;
cout<<"enter the number2"<<endl;
cin>>n2;
try{
if(n2==0)
throw(n2);
else
{
ans=n1/n2;
cout<<"ans="<<ans<<endl;

Prof. Hemchandra Kumbhar Page 50


C++ with Object Oriented Programming

}
}catch(int a)
{
cout<<"Number not divisible by zero";
}

 Exception handling in class:

The exception of user-defined data types such as classes can also be handled. In
this case the throw exception throws an object of class as exception and the catch block
accepts an object of class as argument.

Example1:

#include<iostream.h>
#include<conio.h>
class even
{
int n;
public:
even()
{
n=0;
}
void getdata(int x)
{
n=x;
if(n%2!=0)
throw even();
else
cout<<n<<” divided by 2”;
}
};

void main()
{
int a;
even e;
cout<<”enter a number”<<endl;
cin>>a;
try{
e.getdata(a);
}catch(even)
{
cout<<”exception …”;

Prof. Hemchandra Kumbhar Page 51


C++ with Object Oriented Programming

cout<<a<<” not divided by 2”;


}
getch();
}

Prof. Hemchandra Kumbhar Page 52


C++ with Object Oriented Programming

UNIT V
1. Templates:
1.1. Introduction
1.2. Function Template and examples
1.3. Class Template and examples
2. Working with Files:
2.1. Introduction
2.2. File Operations
2.3. Various File Modes
2.4. File Pointer and their Manipulation

1.1 Templates

1. Template enable to define a generic function or generic class that operates on various data
types instance of creating a separate function or classes for each type. Templates are also
called as generic or parameterized type. Such approach of writing programs is known as
generic programming.
2. The main advantage of using templates is that it reduces the source code size and also
increases code flexibility.
3. When templates are used with function they are known as function templates and when
they are used with classes they are known as class templates.

1.2 Function Templates

In the situation when the same code has to be written for different data type in
overloaded function is called function templates.

The definition of function template is a similar to definition of ordinary function. The


only different is that prefixed by below statement:

Template <class A> // is known as template statement.


Syntax:
Template <class A>
Return data type function name (parameter list)
{
// Function Body
}
Where template and class is a key word and “A” is generic data type Or Template
argument or type parameter

Example:calling function templates

#include<iostream.h>
#include<conio.h>
template <class A>

Prof. Hemchandra Kumbhar Page 53


C++ with Object Oriented Programming

A sum(A x, A y)
{
return x+y;
}
void main()
{
inta,b;
cout<<"\nEnter two integer number";
cin>>a;
cin>>b;
float f1,f2;
cout<<"\nEnter two float number";
cin>>f1;
cin>>f2;
cout<<"\nSum of two int:"<<sum(a,b);
cout<<"\nSum of two float:"<<sum(f1,f2);
}

1.2.1 Function Templates with Multiple Parameters

In this templates statement function has more than one parameter of different data type.

Syntax:
Template <class A, class B>
Return datatype function name (parameter list)
{
// Function Body
}
Example:
#include<iostream.h>
#include<conio.h>
template <class A,class B>
A sum(A x, B y)
{
return x+y;
}
void main()
{
int a;
float b;
cout<<"\nEnter two number";
cin>>a;
cin>>b;
cout<<"\nSum of number:"<<sum(a,b);

Prof. Hemchandra Kumbhar Page 54


C++ with Object Oriented Programming

1.2.2 Function template overloading:

A function template can be overload by another function template having same name with
different number of parameters.

Example:

#include<iostream.h>
#include<conio.h>
template <class A>
A large(A x, A y)
{
if(x>y)
return x;
else
return y;
}
template <class A>
A large(A x,Ay,A z)
{
if(large(x,y)>z)
return large(x,y);
else
return z;
}
void main()
{
cout<<"Largest number(4,2):"<<large(4,2)<<endl;
cout<<"Largest number(4,10,5):"<<large(4,10,5)<<endl;
cout<<"largest number(4.2,5.5):"<<large(4.2,5.5)<<endl;
}

1.3 Class Templates

A class template is used in the situation where two or more class have the same class
definition but handle different data types. A class template must be defined before creating its
object. The definition of class template is similar to the definition of ordinary class except it is
prefixed by below statement.

Template <class A>


Class classname{
//Class body

Prof. Hemchandra Kumbhar Page 55


C++ with Object Oriented Programming

Example:

#include<iostream.h>
#include<conio.h>
template <class A>
class cal{
A x,y;
public:
void getdata()
{
cin>>x;
cin>>y;
}
A sum()
{
return x+y;
}
A sub()
{
return x-y;
}
A mul()
{
return x*y;
}
A div()
{
return x/y;
}
void display()
{
cout<<"\nx+y="<<sum()<<endl;
cout<<"x-y="<<sub()<<endl;
cout<<"x*y="<<mul()<<endl;
cout<<"x/y="<<div()<<endl;
}
};
void main()
{
cal<int>c;
cout<<"Enter two integer:";

Prof. Hemchandra Kumbhar Page 56


C++ with Object Oriented Programming

c.getdata();
c.display();
cal <float> f;
cout<<"Enter two float:";
f.getdata();
f.display();
}

1.3.1 Class template with multiple parameters:

Like function templates, class templates can also have more than one generic data type in the
class template statement.

Example:

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

template <class A,class B>


class clsmulti{
A a;
B b;
public:
void getdata()
{
cin>>a;
cin>>b;
}
void show()
{
cout<<"A:"<<a<<"B:"<<b<<endl;
}
};
void main()
{
clsmulti<int,float>obj1;
cout<<"Enter one int and one float"<<endl;
obj1.getdata();
obj1.show();
}

Prof. Hemchandra Kumbhar Page 57


C++ with Object Oriented Programming

2. Working with Files:

2.1. Introduction

File represents storage medium for storing data or information. Streams refer to sequence of
bytes. In Files we store data i.e. text or binary data permanently and use these data to read or
write in the form of input output operations by transferring bytes of data. So we use the term
File Streams/File handling. We use the header file <fstream>

1. ofstream: It represents output Stream and this is used for writing in files.
2. ifstream: It represents input Stream and this is used for reading from files.
3. fstream: It represents both output Stream and input Stream. So it can read from files
and write to files.

2.2. File Operations

 Creating a file: open()


 Reading data: read()
 Writing new data: write()
 Closing a file: close()

2.2.1 Creating/Opening a File

We create/open a file by specifying new path of the file and mode of operation. Operations
can be reading, writing, appending and truncating. Syntax for file creation:
FilePointer.open("Path",ios::mode);

1. Example of file opened for writing: st.open("E:\data.txt",ios::out);


2. Example of file opened for reading: st.open("E:\data.txt",ios::in);
3. Example of file opened for appending: st.open("E:\data.txt",ios::app);
4. Example of file opened for truncating: st.open("E:\data.txt",ios::trunc);

A file must be opened before you can read from it or write to it. Either ofstream or fstream
object may be used to open a file for writing. And ifstream object is used to open a file for
reading purpose only.

Following is the standard syntax for open() function, which is a member of fstream, ifstream,
and ofstream objects.

void open(const char *filename, ios::openmode mode);

Here, the first argument specifies the name and location of the file to be opened and the
second argument of the open() member function defines the mode in which the file should be
opened.

Prof. Hemchandra Kumbhar Page 58


C++ with Object Oriented Programming

Example: Creating/Opening a File

#include<iostream.h>
#include <fstream.h>
void main()
{
fstreamst; // Step 1: Creating object of fstream class
st.open("E:\\data.txt",ios::out); // Step 2: Creating new file
if(!st) // Step 3: Checking whether file exist
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
st.close(); // Step 4: Closing file
}
}

2.2.2. Writing to a File

While doing C++ programming, you write information to a file from your program using the
stream insertion operator (<<) just as you use that operator to output information to the
screen. The only difference is that you use an ofstream or fstream object instead of the cout
object.

Example: Writing to a File

#include <iostream.h>
#include <fstream.h>

void main()
{
fstreamst; // Step 1: Creating object of fstream class
st.open("E:\\data.txt",ios::out); // Step 2: Creating new file
if(!st) // Step 3: Checking whether file exist
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
st<<"Hello"; // Step 4: Writing to file
st.close(); // Step 5: Closing file
}
}

Prof. Hemchandra Kumbhar Page 59


C++ with Object Oriented Programming

2.2.3. Reading from a File

You read information from a file into your program using the stream extraction operator (>>)
just as you use that operator to input information from the keyboard. The only difference is
that you use an ifstream or fstream object instead of the cin object.

Example:Reading from a File

#include <iostream.h>
#include <fstream.h>
void main()
{
fstreamst; // step 1: Creating object of fstream class
st.open("E:\\data.txt",ios::in); // Step 2: Creating new file
if(!st) // Step 3: Checking whether file exist
{
cout<<"No such file";
}
else
{
char ch;
while (!st.eof())
{
st>>ch; // Step 4: Reading from file
cout<<ch; // Message Read from file
}
st.close(); // Step 5: Closing file
}
}
2.2.4. Close a File

When a C++ program terminates it automatically flushes all the streams, release all the
allocated memory and close all the opened files. But it is always a good practice that a
programmer should close all the opened files before program termination.

Following is the standard syntax for close() function, which is a member of fstream, ifstream,
and ofstream objects.

It is done by FilePointer.close().

Example: Close a File

#include <iostream.h>
#include <fstream.h>
void main()
{
fstream st; // Step 1: Creating object of fstream class
st.open("E:\data.txt",ios::out); // Step 2: Creating new file
st.close(); // Step 4: Closing file
}

Prof. Hemchandra Kumbhar Page 60


C++ with Object Oriented Programming

2.3. Various File Modes

A file must be opened before you can read from it or write to it. Either ofstream or fstream
object may be used to open a file for writing. And ifstream object is used to open a file for
reading purpose only.

Following is the standard syntax for open() function, which is a member of fstream,
ifstream, and ofstream objects.

void open(const char *filename, ios::openmode mode);

Here, the first argument specifies the name and location of the file to be opened and the
second argument of the open() member function defines the mode in which the file should
be opened.

Sr.
Mode Flag Description
No
1 ios::app Append mode. All output to that file to be appended to the end.
2 ios::ate Open a file for output and move the read/write control to the end of the file.
3 ios::in Open a file for reading.
4 ios::out Open a file for writing.
If the file already exists, its contents will be truncated before opening the
5 ios::trunc
file.

2.4. File Pointer and their Manipulation

There are few important functions to be used with file streams like:

1. tellp() - It tells the current position of the put pointer.


Syntax: filepointer.tellp()
2. tellg() - It tells the current position of the get pointer.
Syntax: filepointer.tellg()
3. seekp() - It moves the put pointer to mentioned location.
Syntax: filepointer.seekp(no of bytes,reference mode)
4. seekg() - It moves get pointer(input) to a specified location.
Syntax: filepointer.seekg((no of bytes,reference point)
5. put() - It writes a single character to file.
6. get() - It reads a single character from file.
Example:

#include <iostream.h>
#include <fstream.h>
void main()
{
fstreamst; // Creating object of fstream class
st.open("E:\data.txt",ios::out); // Creating new file

Prof. Hemchandra Kumbhar Page 61


C++ with Object Oriented Programming

if(!st) // Checking whether file exist


{
cout<<"File creation failed";
}
else
{
cout<<"New file created"<<endl;
st<<"Hello Friends"; //Writing to file

// Checking the file pointer position


cout<<"File Pointer Position is "<<st.tellp()<<endl;

st.seekp(-1, ios::cur); // Go one position back from current position

//Checking the file pointer position


cout<<"As per tellp File Pointer Position is "<<st.tellp()<<endl;

st.close(); // closing file


}
st.open("E:\data.txt",ios::in); // Opening file in read mode
if(!st) //Checking whether file exist
{
cout<<"No such file";
}
else
{
char ch;
st.seekg(5, ios::beg); // Go to position 5 from begning.
cout<<"As per tellg File Pointer Position is "<<st.tellg()<<endl;
//Checking file pointer position
cout<<endl;
st.seekg(1, ios::cur);
//Go to position 1 from beginning.
cout<<"As per tellg File Pointer Position is "<<st.tellg()<<endl;
//Checking file pointer position
st.close(); //Closing file
}
}

Prof. Hemchandra Kumbhar Page 62


C++ with Object Oriented Programming

C++ with Object Oriented Programming Question Bank

Unit I
1. Advantages and Disadvantages of Procedure Oriented Programming Languages.
2. What is object oriented? Explain Approaches use to development of software.
3. Explain Advantages and application of OOPs
4. Explain Basic Concept of OOPs.
5. Explain Different between OOPs and POP.
6. Explain important features of object–oriented programming.

Unit II
1. What is class and object explain with example.
2. How to Defining member functions inside and outside of the class.
3. Explain types of Access Specifier in class.
4. Explain Friend class with example
5. Explain constructor and its types
6. Explain Default Constructor with example.
7. Explain Parameterized Constructor with example.
8. Explain Copy Constructor with example.
9. Explain Destructor with example.
10. What is different between constructor and destructors explain?
11. Explain how to pass and return object to and from the function.
12. Write short notes on pointer to object and array of pointer to object.

Unit III
1. What is Polymorphism? Explain Ways to overload a function.
2. What is operator Overloading Explain with example?
3. Explain constructor overloading with example
4. Explain virtual function.
5. Explain pure virtual function with example.
6. Write a short note on pure virtual function and abstract class.
7. Explain data conversion between object and basic types and its type.
8. What is Static Functions explain with example.
9. Write a short note on Virtual destructors and this pointer.

Unit IV
1. What is inheritance? Explain its advantages with example.
2. What is inheritance explain access specifier with syntax.
3. Explain and Write a program to show inheritance with any access specifier.
4. Explain Derived class constructor with example.
5. Explain types of inheritance.
6. Write a short note on Containership and Exception handling
7. What is exception handling explain with example.
8. How to handle exception in class explain with example.

Prof. Hemchandra Kumbhar Page 63


C++ with Object Oriented Programming

Unit V
1. What is Templates? Explain its type
2. What is Templates? Explain Function template with example.
3. What is Templates? Explain Class template with example.
4. What is file handling? Explain File operations and File Modes.
5. Explain File pointers and its functions used in file manipulation.
6. Show the demonstration of open and close file in cpp.

Prof. Hemchandra Kumbhar Page 64

You might also like