CPP With Oop Notes
CPP With Oop Notes
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.1. Introduction
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.
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.
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.
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.
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.
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,
2. Principles 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.
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.
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.
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.
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
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…
}
};
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.
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.
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 ();
}
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();
}
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-
#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();
}
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.
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.
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;
}
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;
}
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)
{
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();
}
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;
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();
}
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;
#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.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
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.
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;
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
}
Example:
#include <iostream.h>
class display
{
public:
display()
{
cout<< "\nCreateObject::" <<endl;
}
~display()
{
cout<< "\nDestroyedObject::" <<endl;
}
};
void main()
{
display x;
}
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:
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.
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.
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.
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);
}
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. 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.
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.
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;
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;
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;
}
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.
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
{
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;
}
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:
#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();
}
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()
{
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();
}
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()
{
Circle C1(10),C2;
C2=C1;
cout<<"C2 Radius:"<<C2.r<<endl;
}
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;
}
void display()
{
cout<<radius<<endl;
}
};
void main()
{
Circle c1,c2( 10.5, 20.4);
c1.display();
c2.display();
}
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.
Example:
#include<iostream.h>
class base
{
public:
virtual void print ()
{
cout<< "print base class" <<endl;
}
void show ()
{
cout<< "show base class" <<endl;
}
};
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
}
Syntax:
classClassname{
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();
}
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.
Example:
#include<iostream.h>
class Base
{
public:
Base(){
cout<<"Constructor in Base"<<endl;
}
virtual ~Base(){
cout<<"Destructor in Base"<<endl;
}
};
void main()
{
Base *basePtr = new Derive();
deletebasePtr;
}
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();
}
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();
}
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.1. Introduction
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
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
// 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
};
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()
{
void main()
{
C c;
}
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;
}
};
void main()
{
Carea c1;
c1.getradius();
c1.showarea();
}
Example:
#include<iostream.h>
class Rlength{
public:
int l;
void getlength()
{
cout<<"Enter Length"<<endl;
cin>>l;
}
};
class Rbreadth{
public:
int b;
void getbreadth()
{
cout<<"Enter Breadth"<<endl;
cin>>b;
}
};
Example:
#include<iostream.h>
class shape{
public:
int radius,l,b;
void carea()
{
cout<<"Area="<<3.1416*radius*radius<<endl;
}
void rarea()
{
cout<<"Area="<<2*(l+b)<<endl;
}
};
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();
}
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;
}
};
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.
Class classname2
{
….
….
};
Class classname3
{
Classname1 obj1;
Classname2 obj2;
…
…
};
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);
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;
}
}catch(int a)
{
cout<<"Number not divisible by zero";
}
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 …”;
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.
In the situation when the same code has to be written for different data type in
overloaded function is called function templates.
#include<iostream.h>
#include<conio.h>
template <class A>
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);
}
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);
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;
}
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.
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:";
c.getdata();
c.display();
cal <float> f;
cout<<"Enter two float:";
f.getdata();
f.display();
}
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>
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.
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);
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.
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.
#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
}
}
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.
#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
}
}
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.
#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().
#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
}
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.
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.
There are few important functions to be used with file streams like:
#include <iostream.h>
#include <fstream.h>
void main()
{
fstreamst; // Creating object of fstream class
st.open("E:\data.txt",ios::out); // Creating new file
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.
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.