301 Oops C++
301 Oops C++
https://www.youtube.com/watch?v=eWHzz-WHQh4
KURUKSHETRA UNIVERSITY,
KURUKSHETRA-136119
BCA III
Lesson No. 01
UNIT – I
Structure: https://www.youtube.com/
watch?v=eWHzz-WHQh4
1.1 Introduction
1.2 Objectives
1
1.5.3 Defining Member Functions
1.8 Static Class members (Static data members & Static member functions)
1.11 Summary
2
1.1 Introduction
Object Oriented Programming is the powerful approach among the programming paradigms and
still means different things to different people. OOP allows decomposition of a problem into a
number of entities called objects and then builds data and functions in object-oriented programs.
The data of an object can be accessed only by the functions associated with that object. However,
functions of one object can access the functions of other objects. Objects, classes, data
genericity are some important features of OOPS. In this lesson, these features are explained in
brief. C++ is most successful and practical object oriented programming language. In C++, the
class forms the basis for object- oriented programming. A class in C++ is almost similar to
structure and can be used interchangeably with minor modifications. Using class or structure, a
programmer can merge one or more dissimilar data types and a new custom data type is created.
A class is nothing but grouping of variables of different data types with functions. Each variable
of a class is called as member variable and functions are called as member functions or methods.
In C++, it is possible to restrict access to data members directly by objects which is not possible
in C. The class is used to define the nature of an object, and it is C++’s basic unit of
1.2 Objectives
3
Define classes and objects.
creating partitioned memory area for both data and functions that can be used as templates for
creating copies of such modules on demand. It attempts to eliminate some flaws encountered in
the procedural approach. A distinguish between Object Oriented Programming & Procedure
Programs are divided into what are known as Large programs are divided into smaller
Data is hidden and cannot be accessed by Data move openly around the system from
New data and functions can be added Function transforms data from one form to
design. design.
4
1.3.1 Features of Object Oriented Programming
i) Object: Objects are basic run time entities in an object oriented system. They may
represent a person, a place, a table of data or any item that the program has to handle.
a state which is represented by the values of its attributes at a particular time .Objects
take up space in memory and has an associated address. When a program is executed,
the objects interact by sending messages to one another. For example, if customer and
account are two objects, then the customer may send a message to the account object
requesting for the bank balance. Figure 1.1 shows a notation for representing an
object.
Object : CUSTOMER
DATA
Customer_name
Account_no
Amount
………..
FUNCTONS
Credit
Debit
Balance
……….
5
ii) Class: A class is a collection of objects of the same kind. In other words, a class is a
attributes and dynamic behaviors common to all objects of the same kind. Once a
class has been defined, we can create any number of objects belonging to that class.
For example, we can define a class called "Student" and create three instances of the
class "Student" for "Peter", "John" and "Tom". Similarly if “Bird” is defined as a
Bird Sparrow;
b) Data members or variables (or attributes, states, fields): contains the static
Class Name
Data Members
(Static attributes)
Member Functions
(Dynamic operations)
6
iii) Information Hiding and Encapsulation: The wrapping up of data and functions
into a single unit is known as encapsulation. The data is not accessible to the outside
world, and only functions which are wrapped in the class can access it. This
insulation of data from direct access by the program is called information hiding.
iv) Data Abstraction: It refers to the act of representing essential features without
including the background details. Classes use the concept of abstraction and therefore
known as Abstract Data Types (ADT). They encapsulate all the essential attributes of
v) Inheritance: The concept of inheritance recognizes that often one defined class is
really just a special case of another class, sharing a lot of common data fields and
methods. It is the process by which objects of one class acquire the properties of the
objects of another class. For example, Car, Motorcycle, and Airplane are all types of
Vehicle. So if a Vehicle class were created that maintained all the state information
common to all vehicle types, then a Car class could be developed that is a
specialization of Vehicle having some common characteristics with the class from
which it is derived as illustrated in figure 1.3 and also dealing with the special
properties that make Cars different from other Vehicle types. In OOP, inheritance
provides the idea of reusability i.e. we can add additional features to an existing class
7
Vehicle
Attributes
………….
Attributes Attributes
…………. ………….
vi) Polymorphism: It means the ability to take more than one form. An operation may
overloading. Similarly we can use a single function name to perform different types
different classes or in same class for different instances. Figure 1.4 illustrates the
concept of polymorphism in which functions with the same name i.e. Area ( ) but
8
SHAPE
Area ( )
communicate with each other by exchanging messages. Objects react when they
request for execution of a procedure and therefore will invoke a function in the
receiving object that generates the desired result. Message passing in figure 1.5
Object name
Communication Operator
Message
Data Elements
9
viii) Genericity: Genericity is an approach which handles a variety of data types by using
generic data types as arguments. A function that works for all C++ data types is
called as generic function. A template is one of the most useful features in C++ which
Ease in software design: Software design is easy as you could think in the problem
space rather than the machine's bits and bytes. You are dealing with high-level
development.
Reusable software: you don't need to keep re-inventing the wheels and re-write the
same functions for different situations. The fastest and safest way of developing a
new application is to reuse existing codes - fully tested and proven codes.
design and develop safe programs that do not disturb the code in other parts of the
program.
10
1.3.3 Applications of Object Oriented Programming
Languages that support OOP features include C++, Smalltalk, Object Pascal and Java. C++ is
most successful, practical, general purpose language and widely used in industry. It is a general-
language with object-oriented data abstraction mechanisms and strong static type safety. C++ is
a superset of C. The three most important facilities that C++ adds on to C are classes,
inheritance, function overloading, and operator overloading. These features enable us to create
abstract data types, inherit properties from existing data types and support polymorphism, thus
C++ is C: C++ supports (almost) all the features of C. Like C, C++ allows programmers to
11
C++ is Object Oriented: C++ enhances the procedural-oriented C language with the
object-oriented extension. The OO extension facilitates design, reuse and maintenance for
complex software.
Template C++: C++ introduces generic programming, via the so-called template. You can
Exception Handling: C++ includes advance feature of exception handling which provides
an integrated approach to detect and report runtime problems in order to take proper action.
STL: C++ provides a huge set of reusable standard libraries, in particular, the Standard
A class provides an approach to pack the data and its related functions together. It can be
ii) Data Members or Variables (or attributes, states, fields): contains the static attributes of
the class.
iii) Member Functions (or methods, behaviors, operations): contains the dynamic operations
of the class.
Classes are created using the keyword class. The declaration of a class is enclosed with curly
braces and terminated by a semi-colon. The member variables and functions are divided into
two sections i.e. private and public. The private and public keywords are terminated by colon
12
(:). The object cannot directly access the member variables and functions declared in private
section. The private members of a class can only be accessed by a public member function of
private:
Declaration of Variables;
public:
Declaration of Variables;
private:
public:
13
double showArea();
};
Defining objects of a class data type is known as class instantiation. When objects are created,
only during that moment memory is allocated to them. They hold the data as well as functions
that handle the data. For example, consider a class Circle. You can create instances of Circle in
Circle c1, c2, *c3; // Construct 3 instances c1, c2, c3 of the class Circle
Here c1, c2 are simple objects and the object *c3 is a pointer to class Circle.
The object can access the public member variables and functions of a class by using dot operator
To access the member function getRadius of class Circle, the statements would be,
c1. getRadius ( );
c2. getRadius ( );
c3 - > getRadius ( );
14
In first two statements, the dot operator ( . ) is used because c1 and c2 are simple objects but in
the third statement, the arrow operator ( - > ) is used because *c3 is a pointer to class Circle.
It should be remember here that the private members are not accessible by the objects directly.
An object can only access the private members through the public member functions.
Sometimes, protected keyword is also used in class declaration whose access mechanism is
similar to private keyword. However, it is frequently used in inheritance. The access difference
between public, private and protected keywords is illustrated in table 1.2 given below:
Access Permission
The member function must be declared inside the class. They can be defined inside or outside the
class. The member function defined inside the class is treated as inline function. If the function is
defined outside the class, its prototype declaration must be done inside the class.
The following program illustrates the use of member function inside the class in public
section.
15
#include <iostream.h>
class Circle
private:
double radius;
public:
radius=1.5;
return radius*radius*3.1416;
};
int main( )
clrscr( );
Circle C1;
C1. getRadius( );
return 0;
16
(ii) Member function outside the class
To define a function outside the class the following steps must be taken:
The function name must be preceded by the class name and its return type separated
#include <iostream.h>
class Circle
private:
double radius;
public:
};
radius=1.5;
return radius*radius*3.1416;
17
int main( )
clrscr( );
Circle c1;
c1. getRadius( );
return 0;
A structure is a user-defined data type with a template that defines a group of logically related
data items of different types. It provides a method for packing together data of different types.
Once the structure type has been defined, you can create any number of variables of that type
using declarations that are similar to the built-in type declarations. In C++ structures were
inherited from the C language. The syntax of structure declaration in C language is as follows:
Variable 1;
Variable 2;
…………..
};
For example:
18
struct Book
char Bname[30];
int Qty;
float Price;
};
In the above example, the keyword struct declares Book as a user-defined data type that holds
The structure name Book can be used to create any number of variables of type Book by using
struct Book B;
Limitations of Structures in C:
They do not allow data hiding as direct access to data members is possible.
C++ has made several improvements in structures to eliminate the limitations of that in C.
In C++, both variables as well as functions can be declared as members in the structures.
19
Structures allow data hiding in C++ as some of their members can be declared as private.
struct Book
private:
char Bname[30];
int Qty;
float Price;
};
Bname = “C++”;
Qty = 2;
Price = 228.5;
20
Printf( “\n Quantity = %d”, Qty);
void main ( )
b1. showbook ( );
b2 -> showbook ( );
OUTPUT
Quantity = 2
Price =228.5
Quantity = 2
Price =228.5
In the above program, private keyword is used in structure declaration to make the data members
private which is not possible in C. Also while declaring the objects, the keyword struct is omitted
21
Relation between Classes and Structures
In C++, structures and classes are almost syntactically similar with a very small difference
between them. Therefore structures can be replaced by the classes by doing some minor
modifications. In fact, the only difference between them is that by default, all the members are
public in structures while by default, all the members are private in classes. In all other respects,
In C++, same variable name can be used to have different meanings in different blocks or
functions in a program. Variable declared inside a block is said to be local to that block and
cannot be accessed outside it. The area or block of the program from where the variable can be
accessed is known as the scope of the variable. In C++ program, the scope of the variable
remains from its declaration till the end of the block containing the declaration. Consider the
following statements:
int m = 20;
………….
………….
……………
……………
22
int m = 30;
…………
…………
Here the two declarations of the same variable m refer to two different memory locations and
having different values. The variable m inside the second block is totally different from the
variable m declared inside the first block. Also in case, the blocks are nested, for example
int m = 20;
………..
………..
int m = 30;
…………
…………
………..
………..
Here in the inner block, the variable m refers to the value declared there in i.e. 30. It hides the
declaration of the same variable in the outer block. Outside the inner block it refers to the data
object declared in the outer block i.e. 20. Thus, the global version of a variable cannot be
accessed from within the inner block. But in C++, a new operator ( : : ) called Scope Resolution
23
Operator is introduced to access the global version of the variable from within the inner block.
Its syntax is
: : variable name
# include <iostream.h>
# include <constream.h>
void main ( )
………..
………..
………..
24
OUTPUT
in inner block
b=2
a=3
: : a =1
In above example the variable a is declared at three places, outside the main ( ), inside the main
( ) and inside the inner block. The output shows that : : a always refers to the global a. In the
The main significance of the scope resolution operator is in the classes to identify the class to
1.8 Static Class members (Static data members & Static member functions)
A static class member has only one copy, belonging to the class instead of the instances. All
instances share the same storage for a static class member. In C++ it is necessary to explicitly
Examples are
static int c;
25
…………….
It can be used to implement "global" class variables and functions that can be used
It can also be used to share information among all instances, e.g., a count on the
A static function can only access static variables, and cannot access non-
static variables. A static function can be referenced without any instantiation (i.e., no
#include <iostream.h>
#include <conio.h>
class Number
static int C;
public:
void count ( )
++C;
cout<< “ \n C =” << C;
26
}
};
int Number :: C = 0;
int main( )
Number a, b, c;
a.count( );
b.count( );
c.count( );
return 0;
OUTPUT
C=1
C=2
C=3
The next example declares the static member functions and call them from the main ( ) function.
#include <iostream.h>
#include <conio.h>
class Num
static int C;
public:
27
static void count ( )
C++;
};
int Num :: C = 0;
int main( )
clrscr( );
Num :: display ( );
Num :: count ( );
Num :: count( );
Num :: display ( );
OUTPUT
Value of C : 0
Value of C : 2
28
1.9 Local Classes
Classes may be defined within a function or a block. Such classes are known as Local classes.
The scope of Local classes is only to that function within which it is defined and not outside of it.
The local class cannot use or access local variables of the functions in which it is
declared.
It can use global variables (declared outside the function) and static variables declared
All the member functions must be declared within the class declaration.
The enclosing function cannot access the private members of a local class.
#include <iostream.h>
#include <conio.h>
void Result ( );
void main ( )
clrscr ( );
Result ( );
29
void Result ( )
class Sum
int a, b;
public:
a = x;
b = y;
int show ( )
return a+b;
};
Sum S;
OUTPUT
Result is 101
30
In the above program, class Sum is defined inside the function Result. The class has two member
functions get ( ) and show ( ). The function get ( ) reads two integers and the function show ( )
When a class is defined with in another class, it is known as nested class. A nested class is valid
within the scope of the enclosing (host) class. To create the object of nested class scope
resolution operator ( : : ) is used by preceding the name of host class. However, the nested
classes are useful in data hiding but due to powerful inheritance mechanism in C++, these are
#include <iostream.h>
#include <conio.h>
class Student
char Name[20];
public:
void getname( )
cin>> Name;
31
void showname( )
int marks;
public:
Marks = a;
void showmarks( )
cout<< marks;
void main ( )
clrscr( );
32
S. getname ( );
T. getmarks(78);
S. showname ( );
T. showmarks ( );
OUTPUT
Ram : 78
In the above program, the class Test is declared inside the class Student and known as nested
1.11 Summary
OOP allows decomposition of a problem into a number of entities called objects and then
The wrapping up of data and functions into a single unit is known as encapsulation.
Inheritance is the process by which objects of one class acquire the properties of the
33
A template is one of the most useful features in C++ which provides supports for generic
programming. Template allows a single function or class to work with different data
types.
approach to detect and report runtime problems in order to take proper action.
C++, Smalltalk and Java are some popular object oriented languages.
A class is a group of variables of different data types with functions. Each variable of a
class is called as member variable and functions are called as member functions or
methods.
The member variables and functions are divided into two sections i.e., private and public.
Objects are created with names. The object declared outside the function is called Global
object. The object declared inside a function body is known as local object.
The member function defined inside the class is treated as inline function.
A static class member has only one copy and all instances share the same storage for
A static function can only access static variables. It can be invoked using the class name.
A structure is a user-defined data type with a template that defines a group of logically
The only difference between the structures and classes is that by default, all the members
are public in structures while by default, all the members are private in classes.
34
The area or block of the program from where the variable can be accessed is known as
Scope Resolution Operator ( : : ) is used to access the global version of the variable from
The main application of the scope resolution operator is in the classes to identify the class
Classes may be defined within a function or a block. Such classes are known as Local
classes. The scope of Local classes is only to that function within which it is defined and
Object Oriented Programming With Ansi & Turbo C++ By Ashok N. Kamthane, Pearson
Education.
35
1.13 Self Assessment Questions
Programming?
3. Differentiate between
5. What is a class? How does a C++ class differ from a C++ structure? Explain by an
example.
8. What are static members and static member functions? Explain with examples.
9. What are Local Classes? How are they differed from simple classes? Explain with an
example.
12. What are the differences between local classes and nested classes?
13. Write a program to declare a class Number and find out the largest number out of the
given numbers.
36
14. Write a program to count the number of vowels present in the string using member
function.
15. Write a program to add two vectors and display the resultant vector. Use classes and
objects.
16. Define a Class Employee. Calculate the Salary for each month including Basic, D.A.,
and Medical after deducting P.F. Also find out the Total P.F. of a employee at the end
of his service using the concept of Static member variables and functions.
17. Write a program to find out the factorial of a given number by using the concept of
Local classes.
18. Write a program to define a class books with suitable member variables like author,
title, price and publisher and member functions like search_book, issue_book and
return_book etc.
37
DIRECTORATE OF DISTANCE EDUCATION
KURUKSHETRA UNIVERSITY,
KURUKSHETRA-136119
BCA III
Lesson No. 02
2.1 Introduction
2.2 Objectives
2.4 Constructors
1
2.7 Default Values to Parameters in Constructors
2.8 Destructors
2.9 Summary
2
2.1 Introduction
In C++, Classes are user-defined data types which act similar to the built-in types. An object is a
class type variable that should be initialized before it can be used. An object contains one or
more individual data member variables. When an object is created, its data member variables, if
not initialized, contain garbage values. The compiler itself cannot carry out the process of
initialization of a variable. The programmer needs explicitly to initialize a variable. It means that
objects should be initialized when they are declared, much the same way as initialization of an
ordinary variable.
Similarly, when an object goes out of scope or no longer required, it should be destroyed and
memory space be released. C++ provides special member functions: Constructor and Destructor.
A Constructor enables an object to initialize when it is created and the destructor destroys the
objects when their presence is no longer necessary. This lesson examines Constructors and
Destructors in detail.
2.2 Objectives
3
2.3 Constructors and Destructors
Constructors and destructors are special member functions of a class. These decide how the
objects are created, initialized, copied, and destroyed. When an object is created, constructor is
executed and member variables are initialized. However, the programmer can also pass values to
the constructor to initialize the member variables with different values. The destructor destroys
the object. The destructor is executed at the end of the function when objects are of no use. Both
Constructors and Destructors have the same name as the class they belong to. The only
2.4 Constructors
Constructors are methods which are used to initialize an object at its definition time. A
constructor is executed when an object is declared. It has same name as that of the class it
belongs. It has neither return value nor void. As other methods, the constructor can take
arguments and be overloaded. A simple example of constructor showing its syntax is as follows:
class Number
int m, n;
public:
……………..
4
};
m = 0;
n = 0;
The following program defines a constructor and initializes the class data members with constant
values.
#include <iostream.h>
#include <conio.h>
class Number
int P,Q,R;
public:
Number ( )
P = 10;
Q = 20;
R = 30;
void display ( )
5
{
};
void main ( )
clrscr ( );
Number X;
X .display ( );
OUTPUT
P = 10
Q = 20
R = 30
In the above program the class Number has a constructor which initializes the data member
variables and a member function which prints the values of data members on the screen. When
an object is created, the constructor is automatically invoked and member variables are
As we know that each object has its own copy of data member variables, therefore every time an
object is created, a constructor is invoked to initialize the member variables i.e. the number of
times of the execution of a constructor is equal to the total number of objects. The following
6
#include <iostream.h>
#include <conio.h>
class Number
int P,Q,R;
public:
Number ( )
P = 10;
Q = 20;
R = 30;
};
void main ( )
clrscr ( );
Number X, Y, Z;
OUTPUT
7
Constructor invoked. P = 10, Q = 20, R = 30
In the above program the class number has three objects X, Y & Z and the output shows that
I. Constructor has the same name as that of the class it belongs to.
VI. They cannot be inherited. However a derived class constructor can call the base class
constructor.
XI. A reference of an object can be passed to the constructor called copy constructor.
8
default constructor
parameterized constructor
copy constructor
Constructors
The constructor without arguments is called as default constructor. The constructors with
As earlier discussed, a constructor that accepts no arguments is called default constructor. The
following program prints the sum of two integers with the help of default constructor.
#include <iostream.h>
#include <conio.h>
class IntegerSum
9
int a, b;
public:
};
a = 5;
b = 10;
return a + b;
void main ( )
clrscr( );
IntegerSum Sum1;
OUTPUT
Sum = 15
10
In the above program, a default constructor is defined which initializes the object Sum1 by
initializes the two integers. The member function display ( ) returns the sum of these two
integers.
In practice, it is required to initialize the various data elements of different objects with different
values when they are created. It is achieved by passing arguments to the constructors when the
objects are created. The constructors that can accept arguments are called parameterized
constructors. In case of constructor with arguments, we need to pass arguments as per the
definition of constructor. They can take any number of arguments. The constructors can take
default arguments also. The arguments can be passed to the constructor functions in two ways:
Let us revise the above program of sum of two integers by using parameterized constructors.
#include <iostream.h>
#include <conio.h>
class IntegerSum
int a, b;
public:
11
a= x;
b = y;
int display ( )
return a + b;
void main ( )
clrscr( );
OUTPUT
Sum = 6
Sum = 60
In the above program the constructor IntegerSum has two arguments i.e. x and y in which the
default value of argument y is zero. It is also called default argument constructor. The statement
IntegerSum Sum1 ( 6 );
assigns the value 6 to x variable and 0 to y variable(by default). However the statement
12
IntegerSum Sum2 = IntegerSum ( 35, 25 );
assigns the value 35 to x variable and 25 to y variable. The actual parameter overrides the default
value here.
A copy constructor is used to initialize an object by using another object of the same class. It is
possible to declare and initialize one object using reference of another object. The argument by
value cannot be passed to the copy constructor. Let us consider the example of class IntegerSum
again.
#include <iostream.h>
#include <conio.h>
class IntegerSum
int a, b;
public:
a= x;
b = y;
{
13
a = I.a;
b = I.b;
int display ( )
return a + b;
void main ( )
clrscr( );
OUTPUT
Sum = 30
Sum = 30
Sum = 30
14
In the above program, class IntegerSum is declared with two member variables a and b and with
two constructors. In the function main ( ), when object Sum1 is created, 10 and 20 are passed to
the constructor and hence constructor with two arguments is invoked. When object Sum2 and
Sum3 are created, the object Sum1 is passed and copy constructor is invoked. The statements
A class can have more than one constructor which are defined with the same name as the class.
But all the constructors should contain different number of arguments. This is known as
constructor overloading. Let us take an example of class Circle containing more than one
constructor.
#include <iostream.h>
#include <conio.h>
class Circle
private:
double radius;
public:
15
radius=0;
radius = r;
radius = c2.radius;
return radius*radius*3.1416;
};
int main( )
clrscr ( );
Circle c3 (c2);
Circle c4=c2;
16
cout<< “ area =” << c3. showArea ( );
return 0;
OUTPUT
area = 38.4846
area = 38.4846
area = 38.4846
In the above program, class Circle is declared with one member variable radius and three
constructors. In the function main ( ), the object c1 is created, no argument is passed i.e. the
default constructor is invoked. When object c2 is created, 3.5 is passed to the constructor and
hence constructor with one argument i.e. parameterized constructor is invoked. When object c3
and c4 are created, the object c2 is passed and copy constructor is invoked.
#include <iostream.h>
#include <conio.h>
class Addition
private:
int a, b, c;
public:
17
Addition ( ) // Default Constructor
{ // No argument
a = 0;
b = 0;
{ // Single argument
a = x;
b = x;
{ // Two arguments
a = x;
b = y;
c = a + b;
return c;
};
int main( )
18
{
clrscr ( );
Addition A1;
Addition A2 (45);
return 0;
OUTPUT
In the above program, class Addition contains three constructors and one member function. The
first constructor receives no argument, the second receives one integer argument and the third
constructor receives two integer arguments. The member function show ( ) returns the sum of
two integers.
A constructor can be defined with default arguments. Consider the declaration of following
constructor:
19
Addition ( int a, int b = 20);
Addition A1 ( 30 );
assigns the value 30 to a and 40 to b. It means the actual parameter, when specified, overrides the
default value of argument. Another point that should be noted here is that the missing arguments
must be the trailing ones. The following program illustrates the constructors with default
arguments.
#include <iostream.h>
#include <conio.h>
class Interest
private:
float Amount;
public:
Principal = p;
year = t;
rate = r;
20
void display_amont ( )
};
int main( )
clrscr ( );
I1. display_amount ( );
I2. display_amount ( );
return 0;
OUTPUT
Principal = 5000
Rate of Interest = 5
year = 3
21
Amount = 750
Principal = 5500
Rate of Interest = 10
year = 5
Amount = 2750
In this program the constructor Interest contains default value to argument r i.e. rate. In case of
object I1 data members Principal and year are initialized to 5000 and 3 respectively whereas the
data member rate takes the default value 5. But for 2nd object I2 the data members Principal, year
and rate are initialized to 5500, 5 and 10 respectively. Here the default value of rate is
overridden.
2.8 Destructors
A destructor is used to destroy the object and release the memory. Destructors take no
arguments. Destruction of objects takes place when the object leaves its scope of definition or is
explicitly destroyed. The latter happens, when we dynamically allocate an object and release it
when it is no longer needed. Destructors are declared similar to constructors. But, they also use
the name prefixed by a tilde (~) of the defining class. For example:
#include <iostream.h>
#include <conio.h>
class Circle
{
22
private:
double radius;
public:
radius=0;
radius = r;
~ Circle ( ) // Destructor
return radius*radius*3.1416;
};
int main( )
clrscr( );
23
Circle c1, c2 (3.5);
return 0;
OUTPUT
area = 38.4846
object destroyed
In this program, the output shows that destructors are automatically invoked when the objects are
no longer required.
I. Destructor has the same name as that of the class it belongs to and preceded by ~ (tilde).
II. Like constructors, the destructors do not have return type and not even void.
VII. They cannot be inherited. However a derived class can call the base class destructor.
24
2.9 Summary
A destructor is a special function used to destroy the object. Destructors are declared
similar to constructors. But, they use the name prefixed by a tilde (~) of the defining
class.
Constructors are of three types: default constructor, parameterized constructor and copy
constructor
When a reference of object is passed as argument to the constructor then it is called copy
constructor.
Like constructors, the destructors do not have return type and not even void.
25
2.10 Suggested Readings
Object Oriented Programming With Ansi & Turbo C++ By Ashok N. Kamthane, Pearson
Education.
10. What is the difference between default constructor and default argument constructor?
11. Write a program to call constructor recursively and hence find out the factorial of a
given number.
26
12. Write a program to add two complex numbers by using multiple constructors in a class.
27
UNIT – II
Manipulators, Friend Function, Friend Class, Arrays, Array of Objects, Passing and Returning Objects to
Functions, String Handling in C++,
Polymorphism: Operators in C++, Precedence and Associativity Rules, Operator Overloading, Unary &
Binary Operators Overloading, Function Overloading, Inline Functions.
DIRECTORATE OF DISTANCE EDUCATION
KURUKSHETRA UNIVERSITY,
KURUKSHETRA-136119
BCA III
Lesson No. 03
3.1 Introduction
3.2 Objectives
3.3 Functions
1
3.7 Friend Functions
3.9 Pointers
3.12 Summary
2
3.1 Introduction
Functions play an important role in C/C++. The large program is divided into a number of
segments i.e. smaller ones and code duplication is avoided. The smaller programs can be written
in the form of functions. Also, it is possible to reduce the size of program by calling and using
the functions at different places in the program. In C++, the method of using functions is slightly
changed and enhanced as compared to C. C++ has added many new features to functions like
function overloading, default arguments, formatting functions etc. to make them more reliable
and flexible. C++ supports two types of functions, namely library functions and user-defined
functions. The library functions are built-in functions that can be used in any program by
including their respective header files. User-defined functions are developed by the user
Pointers are another key aspect of C++ language similar to C. A Pointer is used as tool that can
make programs quicker, straightforward and memory efficient. Pointer variable stores the
memory address of any type of variable. However, the pointer variable and normal variable
should be of same type. This lesson describes the features and applications of functions and
pointers in detail.
3.2 Objectives
3
Understand the concept of Friend Function and Friend Class.
3.3 Functions
coherent task. A large program can be broken down into a number of smaller and self-contained
ones called functions, each of which has some unique and particular purpose. The general form
of function is
return (expression);
The first statement is Function prototype which gives the following details of the function to
the compiler:
I. Name of function
4
Here, Fname is name of function and return_type specifies the type of data that the function
returns. If a function does not return any data then return_type is written as void. The
parameter_list is a comma separated list of variables and their associated types that receive the
value of arguments when the function is called. That is the parameter_list may be written as
(type var1, type var2, …….…… , type var N). Also the function prototype statement
A function prototype can skip the argument names but a function definition cannot. For example
The second part is the function definition which contains the statements called function body.
The return type and the number of arguments and their types must be same in the function
definition as that of function prototype. In function definition, variables names are required
because the arguments must be referenced inside the function. The example of function
definition is
float s = x + y + z;
return s;
This function computes the sum of three numbers and returns the result as float value.
A function is used in the program only when a call to function is invoked. A function must be
called by its name, followed by the actual argument list if any, enclosed within the parentheses
5
and terminated by the semicolon. When a function is called, the control is transferred to the
called function and return back to the calling function after the execution of the called function
or as and when the return statement is executed in it. Consider the following program.
#include <iostream.h>
#include <conio.h>
void main ( )
float l, b, h, vol;
clrscr ( );
cin>> l>>b>>h;
getch( );
float v;
v = x * y * z;
6
OUTPUT
2.5 5 10
Here, in the above program the function volume is called in the main ( ) by using the statement
which contains three actual parameters l, b & h. The control is transferred to the function volume
and formal parameters x, y and z are replaced by the actual parameters l, b and h respectively.
The control is transferred back to the calling function after the execution of return statement and
A function may or may not return a value to the calling function. If it does, the return statement
is used to return value to the calling function. The syntax of return statement is as follows:
return ( expression );
or
return expression;
where expression may be a constant, variable or a expression and parenthesis is optional. The
return statement can also be used without expression. It does not return any value and just acts as
The return statement can return only one value. It can be used anywhere in the function and also
7
{
if ( a > b )
return a;
else
return b;
When the user wants to return more than one values from function, the values should be passed
The parameters or arguments declared in the calling function and specified in the function call
are called as actual parameters or arguments. The parameters or arguments declared in the
function definition are called as formal parameters or arguments. When a function is called the
actual parameters replace the formal parameters. Therefore formal parameters can be viewed as
the place holders for the values passed to them when the function is called. For example:
#include <iostream.h>
#include <conio.h>
void main ( )
8
float x, y, z;
clrscr ( );
cin>> x>>y;
getch( );
float c;
c = a * b;
OUTPUT
5 10
In the above program, variables x and y are actual arguments and variables a and b are formal
arguments. The values of x and y are stored in a and b respectively i.e. the values of actual
arguments are assigned to the formal arguments which are used for computing.
9
There are certain rules regarding parameters that must be observed during the correspondence
i. The actual parameters must be of same data types as its corresponding formal parameters.
ii. The number of actual and formal parameters should be same both in function call and
called function. If formal arguments are more than the actual arguments then the extra
Parameter passing in functions serves the purpose of communication between two functions i.e.
between calling function and the called function. C++ supports three methods by which
i. Call by value: In this method copies of values of actual parameters are passed to
the formal parameters. The formal parameters are just the photocopy of actual
parameters. The operations are performed on the formal parameters and any change in
them does not reflect in the actual parameters. Changes made in the formal arguments are
local to the block of the called function. Once the control returns back to the calling
#include <iostream.h>
#include <conio.h>
void main ( )
10
{
int x, y;
clrscr ( );
cin>> x>>y;
change_value (x,y);
getch( );
int temp;
temp = a;
a = b;
b = temp;
OUTPUT
11
5 10
x = 5 y = 10
In Function change_value
x = 10 y = 5
x = 5 y = 10
In the above program, values of actual arguments x and y are passed to the function
values. The values of a and b are exchanged in this function and control is returned back
to the function main ( ). The output shows that change in values in function change_value
( ) does not reflect in the calling function main ( ) because formal arguments are duplicate
ii. Call by address: In this method, addresses of actual parameters are passed to the
called function. Formal parameters are the pointers which receive the addresses of the
actual parameters. The changes made in the formal arguments are permanent and reflect
in the calling function. Consider the above example again by using this method.
#include <iostream.h>
#include <conio.h>
void main ( )
12
int x, y;
clrscr ( );
cin>> x>>y;
getch( );
int *temp;
*temp = *a;
*a = *b;
*b = *temp;
OUTPUT
5 10
13
Before calling in main
x = 5 y = 10
In Function change_value
x = 10 y = 5
x = 10 y = 5
In the above program, instead of values, addresses of actual arguments x and y are passed
( ) are pointers and receive the addresses of actual parameters. Thus both actual and
formal parameters have same addresses and any change in formal arguments reflects in
the actual parameters. The output shows that change in values of formal parameters a and
b in function change_value ( ) also make the changes in actual arguments in the function
main ( ).
iii. Call by reference: The concept of reference variables in C++ allows us to pass
parameters to the functions by reference. When the arguments are passed by reference,
the formal arguments in the called function become aliases to the actual arguments in the
calling function. It means that when the function is working on formal arguments, it is
actually working on the original data i.e. actual arguments. Therefore changes made to
the formal parameters in the called function become permanent and reflect in the calling
function. This is achieved simply by preceding an address operator ( & ) to the formal
parameters in the function definition. Let us again illustrate the above example.
#include <iostream.h>
14
#include <conio.h>
void main ( )
int x, y;
clrscr ( );
cin>> x>>y;
change_value (x,y);
getch( );
int temp;
temp = a;
a = b;
b = temp;
15
}
OUTPUT
5 10
x = 5 y = 10
In Function change_value
x = 10 y = 5
x = 10 y = 5
In the above program, the formal arguments a and b in function change_value ( ) are the
aliases of actual parameters x and y. Both actual and formal parameters share the same
Similar to variables, an object may be passed to functions by using all the three methods as
a. Call by Value: Here a copy of object is passed to function and any changes made
to formal object inside the function do not affect the actual object. Both actual and formal
b. Call by Reference: In this case address of the object is passed to function implicitly
and the called function works directly on the actual object. This means any changes made
to object inside the called function will reflect to the actual object.
16
c. Call by address: It is similar to Call by Reference except that address of object is
Call by reference and calls by address methods are more efficient because they require to
pass only address of object and not the entire object. Also duplicacy of objects is prevented
as done in call by value. The syntax of passing objects to functions by using all three
#include <iostream.h>
#include <conio.h>
class matrix
int m[2][2];
public:
void getdata( )
int i, j;
17
cin>> m[i][j];
void display ( )
int i, j;
cout<< “\n”;
};
int i, j;
18
}
int main ( )
M1. getdata ( );
M2. getdata ( );
M3. display ( );
return (0);
OUTPUT
m[0] [0] = 4
m[0] [1] = 2
m[1] [0] = 3
m[1] [1] = 1
m[0] [0] = 5
m[0] [1] = 7
19
m[1] [0] = 1
m[1] [1] = 1
9 9
4 2
In the above program, inside the function addition( ), the array variable m refers to object M3
and it is accessed directly because the function is invoked by the object M3. But the members of
M1 and M2 can be accessed only by using the dot operator i.e. M1. m[i]j] and M2.m[i][j]. To
follows:
Also the member variables of objects M1 and M2 can be accessed only by the operator ( -> ) like
A function cannot only accept objects as arguments but also can return them. An object can be
created within a function and returned to another function. The following program of adding two
complex numbers shows how an object can be created and returned to another function.
20
#include <iostream.h>
#include <conio.h>
class Complex
float a, b;
public:
a = real;
b = img;
};
Complex c3;
21
}
int main ( )
Complex X, Y, Z;
cout<< “ X = ”;
X. display( X );
cout<< “ Y= ”;
Y. display( Y );
cout<< “ Z = ”;
Z. display( Z );
return (0);
OUTPUT
X = 5.2 + i 4.0
Y = 3.0 + i 5.6
Z = 8.2 + i 9.6
In the above program, complex number Z gives the sum of the two complex numbers X & Y by
using the friend function Sum( ). The concept of friend function is illustrated in next sections.
22
3.6 Inline Functions
An inline function is similar to macros. Call to inline function in the program, puts the function
code in the caller program. This is known as inline expansion. Inline functions are also called as
open subroutines because their code is replaced at the place of function call in the caller function.
By default all member functions defined inside the class are inline functions. The member
function defined outside the class can be made inline by prefixing the keyword inline to function
inline < return type > < class name> :: function name ( signature)
#include <iostream.h>
class Circle
private:
double radius;
public:
};
radius=1.5;
23
inline double circle :: showArea()
return radius*radius*3.1416;
int main( )
clrscr( );
Circle c1;
c1. getRadius( );
return 0;
The program is same as last one. The only difference is that the functions getRadius( ) and
showArea( ) are defined as inline outside the class. The inline function mechanism reduces the
overhead relating to accessing the member functions. It provides better efficiency and allows
quick execution of functions. Inline functions have one drawback, the entire code of the function
is placed at the point of call in caller function and it must be noted at compile time. Therefore
inline functions cannot be placed in standard library or runtime library. Some precautions should
24
III. Functions should not contain control structures like for loop, while loop, a switch or goto
statement.
In C++, a non-member function can access to the private members of a class. This is possible by
declaring a non-member function friend to the class whose private members are to be accessed.
…………
public:
…………
};
The function declaration should be preceded by the keyword friend. The function is defined as a
normal function anywhere in the program outside the class and its definition does not use friend
keyword.
I. The friend function is not in the scope of the class to which it is declared; therefore it is
25
II. It cannot access the members of a class directly. It has to use object and dot operator to
access the private and public members of a class. For example obj. member, where obj is
IV. It can be declared anywhere in the class without affecting its meaning and scope.
Let us take an example of ‘Account’ class to access its private data like Acc_No. , Name,
#include <iostream.h>
class Account
private:
char name[18];
int acc_no;
float amount;
public:
void getData( )
26
cout << “ \n acc_no :”;
};
float tds;
tds = ac.amount/10;
cout << “\n Tds of account no.” << ac.acc_no << “is Rs.” << tds;
int main ( )
Account Acc;
Acc . getData();
TDS_Cal(Acc);
return 0;
OUTPUT
Name :Amit
27
acc_no :234223
Amount :56000
In this program, the class account has three member variables and one member function. Inside
the class a friend function TDS_Cal is declared and it has authority to access the private
members of the class. The function getData reads the data by keyboard and friend function
More than one function can be declared as friend functions or an entire class can be declared as
friend class. When all the functions of a class need to access another class then that entire class
can be declared as friend class. By default friendship is not mutual i.e., if class A is declared as
friend class of class B, this does not mean that class B has privileges to access private members
of class A. There is an example given below in which values of data members of both classes are
#include <iostream.h>
#include <conio.h>
class Y;
class X
28
int x ;
public:
void read_value1( )
x=25;
};
class Y
int y;
public :
void read_value2( )
y = 45;
};
void X :: display (Y y)
29
void main( )
X x1;
Y y1;
x1. read_value1( );
y1. Read_value2( );
x1.display(y1);
OUTPUT
x=25
y=45
In the above program, class X is the friend class of class Y. It means the member function of
class X can access the data members of class Y. Therefore the display function of class X shows
3.9 Pointers
Pointers are important feature of C and C++ which provide a unique approach to handle data. A
pointer is a derived data type that refers to another data variable. A pointer is defined as a
memory variable that stores the address of another variable of same data type. Figure 3.1 shows
30
Pointer variable Normal variable
Ptr a
4090 10
4090
address of variable
The pointer variable and normal variable should be declared in same manner except that a
pointer variable is preceded by ( * ) asterisk symbol, also called indirection operator. The syntax
For example
int *x, y ;
float *p, q;
x = &y;
p = &q;
In the first statement, x is an integer pointer and it specifies that it can hold the address of any
integer variable. Similarly, in the second statement p is a float pointer and can store the address
of a float variable. In third & fourth statements, addresses of integer variable y and float variable
q are assigned to the pointer x and p respectively by using the ‘&’ address operator. Thus, in the
The indirection operator ( * ) is used in two ways i.e. in declaration as well as act as deference
operator. In declaration, it indicates that variable is a pointer variable. When the pointer is
31
dereferenced, it indicates the value of the variable of which address is stored in it. It means *x
gives the value of y and *p gives the value of q. Consider the following example:
#include <iostream.h>
#include <conio.h>
void main ( )
int *x, y;
clrscr ( );
y = 25;
x = &y;
getch( );
OUTPUT
y = 25 &y = 4078
*x = 25 x = 4078
In the above program, *x is a integer pointer and y is a integer variable. The address of y is
assigned to the pointer x. The ‘&’ operator preceded with the variable y i.e. &y displays the
address of variable y. The output shows that *x displays the value of y and x gives the address of
y.
32
Features of pointers:
i. The memory is utilized efficiently with the pointers. The pointer assigns the memory
ii. The execution time with pointers is faster than the direct access to the memory locations.
iii. Passing arguments to a function by using pointers permits function to modify the actual
arguments.
iv. Pointers are used to pass arrays, strings and functions to functions.
vi. Pointers are used to create data structures like stacks, queues, lists etc.
ix. One pointer can be subtracted from another but addition of two pointers would never
work out.
Consider two pointers P and Q of same type point to the variables X and Y respectively.
The statement P = Q means that content of Q is assigned to P i.e. both P and Q point to
#include <iostream.h>
#include <conio.h>
33
void main ( )
clrscr ( );
X = 15;
Y = 25;
P = &X;
Q = &Y;
P = Q;
getch( );
OUTPUT
Before Assignment
After Assignment
34
The value of P is 6062
The output shows that after assignment both the pointers share the same memory
location.
Comparison: Two pointers can be compared by using relational operators. For example
If ( P = = Q )
Break;
increment or decrement operator. The increment operator moves the pointer to the next
memory location whereas decrement operator moves the pointer to the previous location.
Q--; // decrement
The value of pointer is incremented or decremented by the size of the variable it points
to. For an integer variable, the value of pointer is incremented by 2, for a character it is
a integer pointer with an initial value say 1256 then x++ increments its value by 2 i.e.
subtracting integer from pointers. For example if p and q are pointers then
p = p + 2;
q = q – 2;
35
is legal. If p and q are integer pointers then the above statements increment and
decrement the values of p and q by 2 times the length of a integer variable respectively.
this pointer is used to represent an object that invokes a member function. When a function is
called by an object, the compiler assigns the address of the object to this pointer and then calls
the functions. For example the function call A. display ( ) will set the pointer this to the address
of the object. It means the pointer this acts as an implicit argument to all the member functions.
For example
class Sum
int a = 25;
………..
………..
The pointer this is also used to return the object it points to. The statement is
return *this;
#include <iostream.h>
#include <conio.h>
class Student
36
{
float marks ;
public:
marks = m;
return x;
else
return *this;
void Display( )
};
void main ( )
37
{
S. Display ( );
OUTPUT
Name: Mohit
Marks: 72.5
The above program compares the marks of two students and prints the name and marks of
student with higher marks. Here the pointer this points to the object S1.
In dynamic allocation, the programmers handle the memory allocation and deallocation himself
via new and delete operators. The new operator allocates the memory and returns a pointer to the
start of it. The delete operator frees memory previously allocated using new operator.
Delete pointer_var;
For example:
#include <iostream.h>
38
#include<conio.h>
int main( )
clrscr( );
int *p;
//address to pointer
*p=123;
delete p;
return 0;
The memory can be allocated dynamically to arrays using ‘new’ and deallocated using ‘delete’
operators.
Delete [ ] pointer_var;
An object can be created at runtime. Such an object is called dynamic object. The dynamically
object acts just like any other object. When it is created, its constructor is called. When the object
39
delete ptr;
#include <iostream.h>
#include <conio.h>
class Circle
private:
double radius;
double area;
public:
Circle ( ) // Constructor
area = 0;
radius = 5.6;
~ Circle ( ) // Destructor
area = radius*radius*3.1416;
40
cout<< “\nArea=”<< area;
};
void main( )
clrscr ( );
Circle *C;
C= new Circle;
C -> showArea ( );
delete C;
OUTPUT
constructor
Area = 98.520576
destructor
3.12 Summary
41
The return statement is used to return value to the calling function.
The parameters or arguments declared in the calling function and specified in the
The parameters or arguments declared in the function definition are called as formal
parameters or arguments.
The actual parameters must be of same data types as its corresponding formal parameters.
C++ supports three methods by which parameters can be passed to the functions: call by
In call by value method copies of values of actual parameters are passed to the formal
parameters.
In call by address method, addresses of actual parameters are passed to the called
function.
In call by reference method, the formal arguments in the called function become aliases
Similar to variables, an object may be passed to functions by using all the three methods.
A function cannot only accept objects as arguments but also can return them.
An inline function is similar to macros. The code of inline function is replaced at the
Friend function is a non-member function that can access to the private members of a
class.
The friend function is not in the scope of the class to which it is declared; therefore it is
42
Generally friend functions have the objects as arguments.
When all the functions of a class need to access another class then that entire class can be
Manipulators are special functions which can be used to manipulate the output format.
Manipulators are defined in header file iomanip.h and provide the same features as that of
Users can create their own manipulators for some special purposes.
A pointer is defined as a memory variable that stores the address of another variable of
The pointer assigns the memory space dynamically that leads to save the memory space.
One pointer can be subtracted from another but addition of two pointers would never
work out.
The new operator allocates the memory and returns a pointer to the start of it.
The delete operator frees memory previously allocated using new operator.
43
Object Oriented Programming With Ansi & Turbo C++ By Ashok N. Kamthane, Pearson
Education.
1. Define function. What is the advantage of using functions? Explain with example.
9. Why do you use inline function? Write some precautions for defining the inline
functions.
11. What are friend classes? How can you define them? Explain with an example.
44
13. What do you mean by a pointer? What are the advantages of the pointer variables in the
program?
15. What do you mean by this pointer? Explain the concept of this pointer by giving
suitable example.
21. Write a program to calculate the income tax for the employees using friend functions.
22. Define a class books with suitable member variables like author, title, price and
publisher and member functions like search_book, issue_book and return_book etc.
Use New and delete operators for allocation and deallocation of memory space.
23. Write a program to create a single user-defined manipulator which provides following
a) 12 column width
b) Right justified
24. Write a program to find the greatest of the three numbers using pointers.
25. Write a program to display the memory address of a variable using pointer.
45
26. Write a program to define the increment and decrement operations on pointers.
46
UNIT – II
Manipulators, Friend Function, Friend Class, Arrays, Array of Objects, Passing and Returning Objects to
Functions, String Handling in C++,
Polymorphism: Operators in C++, Precedence and Associativity Rules, Operator Overloading, Unary &
Binary Operators Overloading, Function Overloading, Inline Functions.
KURUKSHETRA UNIVERSITY,
KURUKSHETRA-136119
BCA III
Lesson No. 04
4.1 Introduction
4.2 Objectives
4.3 Arrays
4.6 String
1
4.7 String Functions and Operators
4.9 Summary
2
4.1 Introduction
Arrays are user-defined data structures which hold a collection of homogenous data items. The data
items are called elements of the array and are numbered consecutively 0, 1, 2, ……. These numbers
are called subscripts of the array. Arrays may be one dimensional or multi dimensional depending
upon whether each element of the array is identified by one or more subscripts. The name of array
is a pointer and gives the address of the first element of the array. The address of next element is
given by adding the number of bytes taken by the element depending upon its data type.
String is defined as an array of character type. It is a sequence of characters that contains small and
uppercase letters, numbers and symbols. Each element of string occupies a byte in the memory.
Every string is terminated by the null character. The null character is represented by ‘\0’ whose
ASCII and Hexa-decimal values are zero. C++ provides a new class called string which includes
4.2 Objectives
3
4.3 Arrays
An array is defined as a collection of homogenous data elements (elements of similar data types)
which are located in contiguous memory locations. Each element of array is identified by
specifying the array name, followed by a subscript, enclosed in square brackets. For example
elements of an array A are represented by A[0], A[1], A[2], and so on. The name A is pointer and
gives the address of first element i.e. A[0]. The arrays may be one dimensional or multi
dimensional. The amount of storage required for holding the elements of the array depends upon its
type and size. The size of array is defined by the number of elements contained by the array. The
Like any other data element, an array has to be declared before it is used in the program. The
Here data_type indicates the type of data elements that the array A_name will contain and size
gives the maximum number of elements that can be stored in the array. For example
int A [5];
This declaration defines an array A which consists of five integer data elements that are designated
An array is initialized along with the declaration by placing the data elements separated by commas
4
data_type A_name [ size ] = { list of values };
For example
int A [5] = { 2, 4, 6, 8, 10 };
The above statement declares the array A having five data elements and assigns the values to
A[0] = 2
A[1] = 4
A[2] = 6
A[3] = 8
A[4] = 10
Consider an example:
#include<iostream.h>
#include<conio.h>
void main ( )
int A[5], i;
clrscr ( );
5
getch ( );
OUTPUT
8 15 16 20 25
A[0] = 8
A[1] = 15
A[2] = 16
A[3] = 20
A[4] = 25
The above program input five integers in array A and prints them.
An entire array may be passed to a function by passing the address of first element of the array and
total number of elements that the array contains. As you know that name of the array is a pointer
and gives the address of first element of the array, therefore the whole array may be passed by
passing two arguments i.e. name of the array and total number of the elements of the array. Let us
consider an example of finding the average of marks of the students of a class using functions.
#include<iostream.h>
#include<conio.h>
6
void main ( )
int n, i ;
clrscr ( );
cin>> n;
getch ( );
int i;
avg = sum/n;
return (avg);
7
OUTPUT
45 56 78 67 82
The above program read marks of five students of a class and calls the function Avg_marks ( ) by
passing the address of the array marks [ ] and number of elements of the array. The function
Avg_marks( ) calculates the average of the marks of the students and returns to the calling function.
Arrays can have more than one dimension. Array of an array are known as multidimensional arrays.
The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional
array is, in essence, a list of one-dimensional arrays. Two dimensional arrays are identified by two
subscripts. Similarly, three dimensional arrays are identified by three subscripts and so on. The
Here data_type is the type of the array Array_name and n is the dimensions of the array.
8
A two-dimensional array can be considered as a table or matrix consists of rows and columns. The
above 2-dimensional array A can hold six elements and contains two rows and three columns that
A[ i ][ j ] and 0 ≤ i ≤ 1, 0 ≤ j ≤ 2
Where A is the name of the array, and i and j are the subscripts that uniquely identify each element
in A.
int x [2][2][3];
This array x can hold 12 elements. You can think this example as: Each 2 elements can hold 2
elements, which makes 4 elements and each 4 elements can hold 3 elements. Hence, total number of
You can initialize a multidimensional array in more than one way. Consider an example to initialize
two dimensional array.
Another way to initialize this array with same array elements is as under:
9
and the better way to initialize this array with same elements is as below:
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
void main ( )
clrscr ( );
cin>> x[i][j];
cin>> y[i][j];
10
z[i][j] = x[i][j] + y[i][j];
cout<< setw(4)<<z[i][j];
cout<<endl;
getch ( );
OUTPUT
3 4 6
5 6 8
5 0 8
2 1 1
Resultant matrix is
8 4 14
7 7 9
As discussed earlier, an array is a collection of data elements of similar data types which are stored
in continuous memory locations. It can be of any data type including user-defined data type, created
11
by using class, struct and typedef declarations. Array of variables that is of type class is called array
of objects. An array of objects behaves similar to any other array and usual array accessing methods
are used to access the individual elements. Consider the following class definition:
class Vehicle
char Name[30];
float price;
public:
void getdata ( );
void display ( );
Here vehicle is a user-defined data type and be used to create array of objects related to different
The array Two_wheeler [3] contains name and price information for three objects. Similarly the
Two_wheeler[i].getdata ( );
requests the object Two_wheeler[i] to invoke the member function getdata ( ) and reads the data of
An array of objects is stored inside the memory in the same way as a multi-dimensional array as
12
Name Two_wheeler [0]
Price
Price
Price
#include<iostream.h>
#include<conio.h>
class Vehicle
char Name[30];
float price;
public:
void getdata ( );
void display ( );
};
13
cout<< “ Enter the name:”;
cin>>Name;
cin>>price;
void main ( )
clrscr ( );
Two_wheeler [i].getdata ( );
Two_wheeler [i].display ( );
14
}
INPUT
OUTPUT
Two Wheeler 1
Name: Cycle
Price: 2500
Two Wheeler 2
Name: Scooter
Price: 35000
Two Wheeler 3
Price: 45000
15
In the above program, the statement
creates an array Two_wheeler [3] of three objects of type Vehicle. The function getdata ( ) reads
information and function display ( ) shows the information. Both are invoked by using array of
objects.
4.6 Strings
Operations on C strings require more effort and often become complex. C++ provides a new class
string which allows us to define objects of string type and they can be used as built-in data type in
many situations. For using the string class, the programmer must include < string > in the program.
The string class is very large and contains a number of constructors, member functions and
operators which help us to perform the various operations with strings like creating, reading,
displaying, modifying, comparing and adding string objects, finding the size of strings and many
other operations.
As discussed earlier, in C++ a string is declared as an object. The string object is created and
initialized at once using constructors in the string class. Three most commonly used constructors of
16
Constructors Use
string ( const char * str) To create a string object from a Null terminated string
string ( const string & str) To create a string object from other string object
cin >> S1; // reading string without space through keyboard( one word )
getline( cin, S1); // reading string with spaces through keyboard( a line of text )
Two string objects can be appended by using overloaded + operator. Also the overloaded +=
operator is used to append a string at the end of another string. For example:
S3 += S2; // same as S3 = S3 + S2
The operators << and >> are overloaded to read and display the contents of the string objects.
For example:
cin >> S1; // read string without spaces i.e. one word
The following program illustrates the above mentioned statements of creating string objects.
17
#include< iostream>
#include<string>
int main( )
string S3 ( “ India”);
cin >> S4; // reading through keyboard & delimited by blank space
18
return 0;
OUTPUT
S1 = Hello
Now S1 = Haryana
S4 = Hello
Enter a string
Ansi C++
Now S4 = Ansi
Ansi C++
In the above program, several ways of creating the objects are demonstrated. S4 read only Ansi
using cin and >> as shown in output because only one word can be read using cin and >> but it read
The string class is very large. It includes several constructors (as mentioned above), member
functions and operators which help us to perform various operations with strings. Most commonly
used member functions of the string class are described in the table 4.2 as given below:
19
Function Use
20
The important overloaded operators that can be used with string objects are described in table 4.3 as
given below:
Operator Use
= Assignment
== Equality
!= Not equal to
The substrings and individual characters of a string can be accessed and manipulated in several
ways. The member functions like at( ), find( ), substr( ), find_first_of( ) and find_last_of( ) can
21
be used to access the strings. Consider the following program that makes use of all these functions.
#include< iostream>
#include<string>
int main( )
int a = S1.find(“DAY”);
return 0;
OUTPUT
The string is
DAY is found at : 20
22
E is first found at : 10
E is last found at : 18
DAY
Similarly the contents of the string can be modified by using the functions insert ( ), replace ( ),
#include< iostream>
#include<string>
int main( )
string S1(“HAPPY”);
string S2(“123456”);
23
cout << “ after removal S1 = ”<< S1 << “\n”;
S1.insert ( 3, S2);
S2.replace(1, 4,S1);
return 0;
OUTPUT
S1 = HAPPY
S2 = 123456
after append
S1 = HAPPY123456
24
Also the contents of the string objects can be compared and exchanged by the member functions
#include< iostream>
#include<string>
int main( )
string S1(“Look”);
string S2(“Hook”);
if(d = = 0)
else
S1.swap(S2);
25
return 0;
OUTPUT
S1 = Look
S2 = Hook
After Comparison
After Swapping
S1 = Hook
S2 = Look
4.9 Summary
An array is a collection of homogenous data elements (elements of similar data types) which
The size of array is defined by the number of elements contained by the array.
The name of array is a pointer and gives the address of first element of the array.
Arrays can have more than one dimension. Array of an array are known as multidimensional
arrays. The simplest form of the multidimensional array is the two-dimensional array.
26
An array of objects behaves similar to any other array and usual array accessing methods are
In C, string is declared as a character array. Operations on C strings require more effort and
C++ provides a new class string which allows us to define objects of string type and they
The string class contains a number of constructors, member functions and operators which
help us to perform the various operations with strings like creating, reading, displaying,
modifying, comparing and adding string objects, finding the size of strings and many other
operations.
Object Oriented Programming With Ansi & Turbo C++ By Ashok N. Kamthane, Pearson
Education.
27
4.11 Self Assessment Questions
3. What is the relation between array and pointer? Explain with example.
4. What do you mean by array of arrays? Differentiate between One-dimensional and Two-
dimensional arrays.
5. What do you mean by array of objects? How they are stored in memory? Explain with
example.
6. What do you mean by string? Explain the methods of creating string objects.
8. Describe the various overloaded operators used to manipulate the strings in C++.
begin ( )
append ( )
at ( )
erase ( )
max_size ( )
resize ( )
capacity ( )
assign ( )
28
12. Write a program to declare 2-dimensional array of characters. Store ten names in array and
15. Write a program to count the number of vowels and spaces in the given string.
16. Write a program to append the same string in the reverse order to the end of the string.
17. Write a program to remove all duplicate letters from the given string.
18. Write a program to display the string elements one by one using member function at ( ).
22. Write a program to assign a sub-string from main string to another string.
29
UNIT – II
Manipulators, Friend Function, Friend Class, Arrays, Array of Objects, Passing and Returning Objects to
Functions, String Handling in C++,
Polymorphism: Operators in C++, Precedence and Associativity Rules, Operator Overloading, Unary &
Binary Operators Overloading, Function Overloading, Inline Functions.
KURUKSHETRA UNIVERSITY,
KURUKSHETRA-136119
BCA III
Lesson No. 05
Compile-Time Polymorphism
UNIT – II
Structure:
5.1 Introduction
5.2 Objectives
5.3 Operators
1
5.3.8 Scope Resolution Operator
5.7 Summary
2
5.1 Introduction
Polymorphism means the ability to take more than one form. It plays an important role in allowing
objects with different internal structure to share the same external interface. It is characterized by
the term “One interface and multiple methods”. Polymorphism (as shown in figure 5.1) is
categorized into two types: Compile-Time (Static) Polymorphism and Run-Time (Dynamic)
Polymorphism, depending on whether an object is bound to its function call at compile time or at
run time.
POLYMORPHISM
3
Binding of an object to function at compile time is called Compile-Time Polymorphism or static
Binding and binding of an object at run time is called Run-Time Polymorphism or dynamic
Binding.
more than one definition for a function name or an operator in the same scope is called function
overloading and operator overloading respectively. In Function overloading, a single function name
is used to perform different tasks by using different number and different types of arguments.
In this lesson we also discuss about operators, their precedence and associativity, function
5.2 Objectives
Understand and describe the precedence and associativity of operators and their role in
computations.
Describe and give different examples of Function Overloading and Operator Overloading.
4
5.3 Operators
An operator is a symbol/word that tells the compiler to perform specific operation. C++ is rich in
built-in operators and provides the following types of operators as shown in Table 5.1:
Assignment Operators =
Comma Operator ,
Conditional Operator ?:
There are some additional operators in C++, which are discussed in Table 5.2:
5
Operators Description
division etc. They can be both unary as well as binary operators. Table 5.3 shows the list of
arithmetic operators with associativity in the order of their precedence. The unary minus ( - ) and
6
unary plus ( + ) have higher precedence. The unary minus multiplies the operand by -1 and unary
plus ( + ) multiplies its operand by +1. The operators *, / and % are on the same level of precedence
having higher precedence than binary + and binary – but lower than that of unary minus and unary
plus arithmetic operators. The operators *, /, %, + and – perform their usual operations as they do in
most other computer languages. Also it should be remembered that parentheses can alter the order
to have higher level of precedence. It means that the operators of lower precedence can be evaluated
before the operators having higher precedence by placing them with in parentheses in an
expression. However operators within the parentheses follow the usual precedence order. Also
when operators have same precedence, the expression is evaluated from left to right.
2 Left to Right
Multiplication, Division,
*, /, %
Modulus/Remainder operator
Relational operators define relationship between the operands. Expressions that use relational
operators return ‘0’ if the condition is false and ‘1’ if the condition is True. Table 5.4 shows the list
7
Operator Description Associativity
‘<’ Checks whether the value of left operand is less than the Left to Right
< ( Less than)
value of right operand, if yes then condition becomes true.
‘==’ Checks whether the values of two operands are equal Left to Right
== ( Equal to)
or not, if yes then condition becomes true.
!= ( Not equal ‘!=’ Checks whether the values of two operands are equal or
to) not, if values are not equal then condition becomes true.
All the Relational operators are lower in precedence than Arithmetic operators. That is the
expression 20 > 14 + 15 is evaluated as if it were written 20 > (14 + 15) and the result is false. The
operators <, <=, >, >= have equal precedence and the operators = =, ! = are in same group of
8
precedence but lower than <, <=, >, >=. All the Relational operators have left to right associativity.
2. = =, != Lower Precedence
Logical operators provide the ways to connect the relationships that the operands can have with one
Operator Meaning
|| Logical OR
! Logical NOT
a b a && b a||b !a
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0
Expressions that use logical operators return 0 for false and 1 for true. Relational and logical
9
Because here both the expressions are true.
Logical operators are lower in precedence than arithmetic and relational operators and their
associativity is left to right. Table 5.7 shows the associativity and precedence order of logical
operators.
|| 2 Left to Right
! 3 Left to Right
Bitwise operators are used to operate the data at bit level. Bitwise operation refers to testing,
setting, or shifting the actual bits in a byte or word corresponding to the int and char data types
only. These operators cannot be used with float, double, long double, void, bool or other complex
Operator Meaning
| bitwise OR
^ bitwise exclusive OR
~ One’s Complement
10
&, | and ^ are binary operators and produce usual output at bit level as given by AND, OR and Ex-
OR operations. The complement operator ( ~ ), left shift ( << ) and right shift ( >> ) are unary
operators. The complement operator inverts all the bits in a given expression i.e. 0 to 1 and 1 to 0.
For example
The left shift operator shifts the bit patterns a number of bits to the left and blank spaces produced
X<< m
Where X is the operand and m is the number of bits to be shifted to the left.
For example
X = 10101010
X << 4 = 10100000
The right shift operator shifts the bit patterns a number of bits to the right and blank spaces
produced at the left are padded with 0’s. The general syntax is
X >> m
Where X is the operand and m is the number of bits to be shifted to the right.
For example
X = 10101010
X >> 4 = 00001010
#include<iostream.h>
#include< iomanip.h>
#include<conio.h>
11
void main ( )
clrscr ( );
getch ( );
OUTPUT
x&y = 0
x|y = 30
x^y = 30
~x = -11
x<<2 = 40
x>>2 = 2
Here as size of int data type is 16 bit, therefore all the operations are carried out on 16 bit binary
numbers. The binary form of above output is explained in the table 5.9 given below:
12
Operation Binary Equivalent Decimal Equivalent
~x is equivalent to decimal 65525 but the range of an integer is -32768 to +32767. Therefore after
^ 4 Left to Right
| 5 Left to Right
13
5.3.5 Increment and Decrement operators
The increment (++) operator adds 1 to its operand and the decrement (- -) operator subtracts 1 from
its operand. Both the increment and decrement operators may either precede (prefix) or follow
(postfix) the operand. These operators transform a variable into a statement expression. In other
words:
X++;
is equivalent to
X = X + 1;
and
X - -;
is equivalent to
X = X – 1;
Also
X = X + 1;
can be written
++X;
or X++;
However there is a difference between the prefix and postfix forms when you use these operators in
operand first before using it in the expression whereas the post-increment or post-decrement
operator increases or decreases the value of variable after using the prior value of operand in the
X = 5;
14
Y = -- X;
Here the value of X and Y is 4. But if you rewrite the above statement as
Y = X --;
Similarly if X = 10 and Y = 20
Then the value of X * ++Y is 210 because the value of Y is incremented first before using it in the
expression. But the value of expression X * Y++ is equal to 200 as the value of Y is incremented
The precedence of both increment and decrement operators is same and the associativity is right to
left.
C++ contains a ternary operator pair ? : that replaces the if - then - else statements. The general
form is
the expression 1 is evaluated first. If it is true, expression 2 is evaluated and becomes the value of
the expression. If expression 1 is false, expression 3 is evaluated and becomes the value of the
a = 20;
b = a >15 ? 50 : 60;
since the value of a is greater than 15 , the condition is true and b is assigned the value 50. The
a = 20;
15
if ( a > 15)
b = 50;
else
b = 60;
The sizeof is a unary operator which returns the size of operand in bytes. The operand may be a
sizeof (var);
#include<iostream.h>
#include< iomanip.h>
#include<conio.h>
void main ( )
clrscr ( );
getch ( );
16
OUTPUT
size of char is 1
size of int is 2
size of float is 4
size of double is 8
In C++, a new operator ( : : ) called Scope Resolution Operator is introduced to access the global
value of the variable from within the inner block. Its syntax is
: : variable name
For example : : m access the global value of variable m whereas m allows us to access the local
#include< istream.h>
#include<conio.h>
void main ( )
clrscr( );
getch ( );
17
}
OUTPUT
Global x = 25
Local x = 35
The complete precedence and associativity of all the operators discussed in this lesson are given in
18
5.5 Unary and Binary Operators
Based upon number of operands, the operators are of two types - Unary and Binary. Unary
operators have only one operand. The examples of unary operators are ++ (increment), --
(decrement), & (address), * (indirection/content of), + (unary plus), - (unary minus) etc. Unary
operators have higher precedence over binary operators. In “++B” the “++” operator has only one
On the other hand, binary operators (”bi” means “two”) have two operands. For instance, in “A *
B”, the ‘*’ operator has two operands ‘A’ and ‘B’. The “-” and “+” operators can be both unary and
binary, in “-4” or “+4” it denotes a negative or a positive number i.e. unary operator, in “9 – 4” it
All Unary and Binary operators are listed in a Table 5.12 given below:
++ Increment Unary
–– Decrement Unary
19
~ complement Unary
, Comma Binary
!= Inequality Binary
% Modulus Binary
* Multiplication Binary
+ Addition Binary
– Subtraction Binary
/ Division Binary
20
<<= Left shift assignment Binary
= Assignment Binary
== Equality Binary
^ Exclusive OR Binary
Bitwise inclusive OR
|= Binary
assignment
|| Logical OR Binary
Compile-Time Polymorphism means an object is bound to its function call at compile time. It is
21
also called static binding or early binding. It is implemented by the overloaded functions and
operators. The information regarding the overloaded member functions and operators are known to
the compiler at compile time. Compile-Time Polymorphism is of two types: Function overloading
Function Operator
Overloading Overloading
The same name can be used to create a number of functions that perform different tasks. Defining
multiple functions with the same name is known as function overloading or function polymorphism.
The overloaded functions must be different in number of arguments or types of arguments or order
of arguments. If two functions have the same number of arguments and same types then they cannot
be overloaded. The example shows the overloaded function find_Area to find the area of triangle,
22
#include <iostream.h>
#include <conio.h>
void main( )
clrscr( );
int areaR;
float areaT;
float areaC;
areaR = find_Area(5,15);
areaT = find_Area(5.5,1.5);
areaC = find_Area(5.3);
getch( );
return ( len * bh );
23
int find_Area(double bs , double ht)
return (0.5 * bs * ht );
return ( 3.142857 * r * r );
OUTPUT
area of rectangle is 75
b) Variable should be passed instead of passing constants directly. It will avoid ambiguity.
c) In function overloading, more than one function has to be actually defined and occupy
memory.
d) Only the functions that basically perform the same types of tasks, on different sets of
24
5.6.2 Operator Overloading
Operator overloading is an important mechanism in C++ which gives new definition to an operator.
The built-in operators are redefined to operate on objects. To define an additional task to an
operator, a special function called operator function which describes the task is used. The general
Function body
Here, return type is the type of value returned by the specified operation and operator is overloaded
operator and it is preceded by the keyword operator. Operator functions may be either member
function or friend function. The difference between them is that a friend function will have only one
argument for unary operators and two for binary operators whereas a member function has no
argument for unary operators and single argument for binary operators. Almost all the operators in
Conditional operator ( ? : )
25
5.6.2.1 Overloading Unary Operators
Unary operators operate on one operand. The unary minus (-) operator is used to change the sign of
the operand it acts upon. This operator works well with basic data types such as int, float, etc. By
overloading this operator, it can work the same way for user defined data types as it does for basic
data types, i.e. change the sign of the operand. The unary minus operator function does not take
any arguments but it changes the sign of all the data members of the object that calls this function.
Since this function is a member function of the same class, it can directly access the members of the
Following is the program which overloads the unary minus (-) operator.
#include <iostream.h>
#include<conio.h>
class Unaryop
int a;
int b;
int c;
public :
a=x;
b=y;
c=z;
26
}
void operator – ( );
};
a = -a;
b = -b;
c = -c;
int main( )
clrscr( );
Unaryop U;
U. readdata ( 5 , -15, 25 );
U. show ( );
27
cout << “after :” ;
U. show ( );
return 0;
OUTPUT
Before : 5 -15 25
After : -5 15 -25
It receives only one class type argument explicitly, in case of operator as a member function and
returns a class type. For a friend function, two class types are received as arguments.
Following is the example that can be used to add two Box objects and returns final Box object by
overloading operator +.
#include <iostream.h>
#include<conio.h>
class Box
private:
double length;
double breadth;
28
double height;
public:
length = ln;
breadth = bh;
height = ht;
double Volume(void)
Box box;
return box;
};
29
int main( )
Box Box1;
Box Box2;
Box Box3;
Box1.setDimensions(4.0,6.0,8.0);
Box2. setDimensions(5.0,7.0,9.0);
volume = Box1.Volume( );
volume = Box2.Volume();
volume = Box3.getVolume();
return 0;
OUTPUT
30
The above program calculates the individual volumes of two boxes and then finds the volume of
third box equivalent to the total volume of both boxes if combining them.
Operators may be overloaded by using Friend functions also. The difference is that a friend function
will have one argument for unary operators and two for binary operators whereas a member
function has no argument for unary operators and single argument for binary operators.
The Box program discussed in the previous section can be modified using a friend operator function
as follows:
#include <iostream.h>
#include<conio.h>
class Box
private:
double length;
double breadth;
double height;
public:
double Volume(void)
31
void setDimensions( double ln, double bh, double ht )
length = ln;
breadth = bh;
height = ht;
};
Box operator + (Box b1, Box b2) // Overload ‘+’ to add two Box objects.
Box box;
return box;
int main( )
Box Box1;
Box Box2;
Box Box3;
Box1.setDimensions(4.0,6.0,8.0);
32
Box2. setDimensions(5.0,7.0,9.0);
volume = Box1.Volume( );
volume = Box2.Volume();
volume = Box3.getVolume();
return 0;
OUTPUT
5.7 Summary
static Binding and binding of an object at run time is called Run-Time Polymorphism or
dynamic Binding.
33
In Function overloading, a single function name is used to perform different tasks by using
an operator.
Overloading of operators can be categorized in two types i.e. Unary operator Overloading
Some operators i.e. Class member access operators (. , .*), Scope resolution Operator ( :: ),
A unary operator requires one operand and a binary operator needs two operands whereas a
Relational operators define relationship between the operands whereas logical operators
provide the ways to connect the relationships that the operands can have with one another.
Bitwise operators are used only with the int and char data types only.
The pre-increment or pre-decrement operators first changes its operands value and then uses
34
A non-member function called friend function can access to the private members of a class
Object Oriented Programming With Ansi & Turbo C++ By Ashok N. Kamthane, Pearson
Education.
Polymorphism?
3. What is Function Overloading? What are the rules for defining overloaded functions?
5. What do you mean by operator precedence? Explain the relative precedences of different
operators.
35
6. What do you mean by associativity of operators?
8. Describe the various arithmetic operators and the rules associated with their use in C++.
10. What are logical operators? With what types of operands can they be used and what type of
resultant is obtained?
11. What is the significance of bitwise operators? Explain with suitable examples.
12. What is the difference between prefix and postfix increment/decrement operators? Give
suitable examples.
14. What is the significance of scope resolution operator? Explain it by giving suitable
examples.
15. What is operator overloading? What are the rules for overloading operators?
17. What do you mean by Unary operators? How are they overloaded? Explain it with an
example.
18. What do you mean by Binary operators? How are they overloaded? Explain it with an
example.
21. How are friend functions used to carry out overloading of operators?
22. Write a program to convert the temperature in degree Fahrenheit into its equivalent degrees
Celsius.
36
23. Write a program to calculate the sum of digits of a five digit number.
25. Write a program to calculate the income tax for the employees using friend functions.
26. Write a program to calculate absolute value of long and float number using function
overloading.
27. Write a program to overload a function to convert an integer number to an ASCII character
28. Write a program to overload the function ‘volume’ which returns volume of different shapes
29. Write a program to overload ‘ > ’ operator to display the largest object out of the two
objects.
32. Write a program to overload Binary operator ‘+’ to find the addition of two complex
numbers.
33. Write a program to perform addition and subtraction of two matrices by overloading ‘+’ and
‘–’ operators.
37
UNIT – II
Manipulators, Friend Function, Friend Class, Arrays, Array of Objects, Passing and Returning Objects to
Functions, String Handling in C++,
Polymorphism: Operators in C++, Precedence and Associativity Rules, Operator Overloading, Unary &
Binary Operators Overloading, Function Overloading, Inline Functions.
KURUKSHETRA UNIVERSITY,
KURUKSHETRA-136119
BCA III
Lesson No. 06
Dynamic Polymorphism
UNIT – III
Structure:
6.1 Introduction
6.2 Objectives
1
6.8 Constructors and Virtual Functions
6.10 Summary
2
6.1 Introduction
achieved by the use of virtual functions. If function is bound at compile time then it is early or
static binding and if function is bound at run time then it is late or dynamic binding. In this lesson,
6.2 Objectives
Polymorphism is divided into two types on the basis whether the function call is bound to the
function at compile time or run time. Types of polymorphism are shown in figure 6.1. Deciding the
binding of function call to the function at compile time is called early or static binding and is
accomplished by function overloading and operator overloading whereas deciding the binding of
function call to the function at run time is called Late or dynamic binding and is achieved by
3
virtual functions. In a situation where the function name and prototype is same in both base and
derived classes i.e. base class function is exactly same in number and types of parameters with the
derived class function then function is not overloaded. Therefore static binding does not apply.
But if the function is declared virtual then system will use dynamic binding and run time
polymorphism is achieved.
POLYMORPHISM
Pointer is an important aspect of C++ which provides a technique to handle data. It is a derived
data type which stores the memory address of another variable. It is declared as
4
data-type * Pointer variable;
Here data-type is the valid data type in C++ like int, char etc and pointer variable is the name of
the pointer. The asterisk ( * ) symbol distinguishes a pointer variable from other variables.
Similarly a pointer can point to an object created by the class. The object pointer is declared as
Object pointers are used in creating the objects at run time and can be used to access the public
members of the class. The public member functions of the class are accessed by the syntax
class Employee
int Emp_id;
float salary;
public:
Emp_id = e;
salary = s;
void showdata ( )
5
{
};
void main ( )
clrscr ( );
Employee E;
OUTPUT
Employee id : 234
In this program, Etr is the object pointer which refers to the object E of the class Employee. The
are equivalent to the normal access using dot operator and the object i.e.
E . showdata ( );
6
6.5 Virtual Functions and its need
As earlier discussed, when the base class and derived class have the function with same prototype
then the functions are not overloaded and ambiguity arises. The object of the derived class invokes
only the member function of the derived class i.e. the member function of the derived class
overrides the member function of the base class. This feature is called function overriding.
However the base class function can be invoked by the derived class object using the scope
resolution operator. The given program shows the use of scope resolution operator.
class Base
int a ;
public:
Base ( )
a = 20;
void show ( )
cout<< “ \n a = ” << a;
7
};
int b;
public:
Derived ( )
b =25;
void show ( )
};
void main ( )
clrscr ( );
Derived D;
D. Base :: show ( );
D. show ( );
8
OUTPUT
a = 20
b = 25
In the above program to invoke the base class function the base class name with scope resolution
The main requirement of polymorphism is the ability to refer to objects without any regard to their
classes. It means a single pointer variable that refers to the objects of different classes must invoke
the functions of respective classes. Let us take a program in which a pointer to the base class is
class Base
int a ;
public:
Base ( )
a = 20;
void show ( )
9
cout<< “ \n a = ” << a;
};
int b;
public:
Derived ( )
b =25;
void show ( )
};
void main ( )
clrscr ( );
Base S, *ptr;
Derived D;
ptr = &S
10
ptr -> show ( );
ptr = &D
OUTPUT
a = 20
a = 20
From the output, it is observed that a base class pointer even it is made to refer the object of
derived class, always executes the function of base class. Thus the polymorphism is not achieved.
When the same function name with same prototype is used in the both base and derived classes,
the function in the base class is declared as Virtual using the keyword virtual preceding its normal
declaration. Virtual functions can only be member functions. Run-time polymorphism is achieved
only when a virtual function is accessed by a pointer to the base class. The syntax of declaring the
………………
………………
11
# include < iostream.h>
class Base
int a ;
public:
Base ( )
a = 20;
cout<< “ \n a = ” << a;
};
int b;
public:
Derived ( )
b =25;
12
}
void show ( )
};
void main ( )
clrscr ( );
Base S, *ptr;
Derived D;
ptr = &S
ptr = &D
OUTPUT
a = 20
b = 25
13
The difference is the use of virtual function and a base class pointer variable by referring the
derived class object also invokes the derived class function. The virtual keyword performs the run-
time polymorphism. In first call, the show ( ) function in the base class is invoked and in next call
after referring the object of derived class, show ( ) function of derived class is executed.
Let us take another practical example to find area of different shapes using Virtual functions.
Consider a base class shape which accepts two values to calculate the area of figures having virtual
function and two derived classes rectangle and triangle in which virtual function is redefined.
class Shape
protected:
double len , bd ;
public:
len = x ;
bd = y ;
14
};
public:
void show_area ( )
};
public:
void show_area ( )
};
void main ( )
clrscr ( );
Rectangle R;
15
R . get_data (5.6, 7.5)
Triangle T;
Shape *area[2];
OUTPUT
area of rectangle = 42
In the above program, shape is the base class which accepts two values length & breadth for
rectangle and height & base for the triangle. The function show_area( ) is the virtual function
which displays the area of particular shapes and redefined in both the derived classes. In main
function area[0] and area [1] refer to the objects R and T of derived classes rectangle and triangle
respectively which invokes the show_area ( ) functions defined in the derived classes.
16
III. The virtual functions should not be static.
IV. Constructors cannot be declared as virtual but virtual keyword can be used before the
destructors.
VI. The virtual function must be defined in the public section of the class.
VIII. The prototype of virtual functions in the base class and derived class should be same.
X. A base pointer can point to any type of the derived class object, but the reverse is not
true i.e. a pointer to a derived class object cannot access the object of base class.
XI. If a virtual function is not redefined in the derived class, the function call invokes the
The member functions of base classes are rarely used for doing any task in practical applications.
It only serves as a place holder. Such types of virtual functions inside the base class which perform
no task are called dummy functions or do-nothing functions or pure virtual functions. We can
define a virtual function as a function declared in the base class that has no definition relative to
For example
17
virtual void Show ( ) = 0;
The function Show ( ) is a pure virtual function. The assignment to zero indicates that the function
The class having pure virtual function cannot be used to declare any object and such classes are
called abstract classes. Let us reconsider the previous program. Now the base class function is
class Base
protected:
int a ;
public:
Base ( )
a = 20;
};
18
int b;
public:
Derived ( )
b =25;
void Show ( )
};
void main ( )
clrscr ( );
Base *ptr;
Derived D;
ptr = &D
OUTPUT
a = 20
b = 25
19
In the above program, the Show function of Base class is made pure virtual function i.e. it does
nothing. The pointer object ptr refers to the derived class and invokes the derived class function
Show ( ). We cannot invoke the base class function Show ( ) by using the object pointer.
As earlier discussed the classes which cannot be used to declare objects are called abstract classes.
All other classes which can be used to create objects are called concrete classes. Any attempt to
declare object from abstract class gives rise to an error message by the compiler. Abstract classes
are just like a skeleton and programmers use them only to extend. Regarding abstract classes, the
III. The objects of derived classes can be declared. It means derived classes cannot be made
abstract.
The abstract classes containing virtual function can be used for help in program debugging. Let us
class Debug
public:
20
virtual void show ( )
};
int x;
public:
X()
x =5;
void show ( )
};
int y;
21
public:
Y()
y = 15;
};
void main ( )
clrscr ( );
X x1;
Y y1;
x1. show ( );
y1. show ( );
OUTPUT
in class X x = 5
Here classes X and Y are derived from the abstract class Debug. x1 and y1 are the objects of the
derived classes X and Y. The statement x1. show ( ) invokes the function show ( )and value of x is
displayed. The object y1 also invokes the function show ( ) but the class Y does not have the
function show ( ). Therefore the function show ( ) of abstract base class is executed which displays
a warning message.
22
6.8 Constructors and Virtual Functions
Constructors cannot be declared as virtual. It is necessary to know the information about the exact
type of the object in order to construct it. However it is possible to invoke a virtual function using
constructor. When a virtual function is invoked through a constructor, the derived class member
class X
int a;
public:
X()
a = 5;
};
23
class Y : public X
int b;
public:
Y( )
b = 15;
X *x ;
x = this;
x -> display ( );
void display( )
};
void main ( )
clrscr ( );
X x1;
Y y1;
24
OUTPUT
b = 15
In the above program, both the base class and derived class contain constructors. In the
derived constructor, a base class pointer *x is declared. This pointer refers to the object of calling
member function i.e. object y1 and therefore pointer x invokes the derived class member function
display ( ).
Destructors can be declared as virtual and called as virtual destructors. The virtual destructors are
implemented just like the virtual functions. When a derived class object referred by the base class
object pointer is deleted, destructors of derived class and base classes are executed. The following
public:
X()
25
}
virtual ~X ( )
};
public:
Y()
~Y ( )
};
void main ( )
clrscr ( );
X *ptr;
ptr = new Y;
26
delete ptr;
OUTPUT:
In the above program two classes X and Y are defined with constructors and destructors. The
destructor of base class X is declared as virtual. In the function main ( ) a derived class object is
constructed using the new operator whose address is hold by the base class pointer ptr. As seen in
the output, when ptr is destroyed using the delete operator, the destructor of derived class and then
6.10 Summary
Run-time polymorphism also known as dynamic binding is the link between function
Dynamic or late binding is accomplished by the virtual functions only when a virtual
function is accessed through a pointer to the base class. The keyword virtual prevents
The virtual functions must be member functions of class and should not be static.
27
The object of derived class can access not only its own members but also the members
The prototype of virtual functions in the base class and derived class should be same.
A virtual function declared in the base class that has no definition relative to the base
The class having pure virtual function cannot be used to declare any object.
The classes which cannot be used to declare objects are called Abstract classes.
All the derived classes without pure virtual function are called Concrete classes.
Virtual destructors are implemented in the same way like virtual functions.
Object Oriented Programming With Ansi & Turbo C++ By Ashok N. Kamthane,
Pearson Education,
28
2. What is the difference between static and dynamic binding?
4. What are virtual functions and why are they used? Explain with an example.
5. Define pure virtual function. How are they created? Explain with an example.
6. Explain the significance of pure virtual function with the help of an example.
12. Write a program to invoke member functions of base class and derived classes using
14. Write a program on a book shop which sells books and audio tapes for displaying the
details of both items. Create a base class media that stores title and price of item and two
29
DIRECTORATE OF DISTANCE EDUCATION
KURUKSHETRA UNIVERSITY,
KURUKSHETRA-136119
BCA III
Lesson No. 07
Inheritance in C++
UNIT – IV
Structure:
7.1 Introduction
7.2 Objectives
7.3 Inheritance
1
7.4.3 Multiple Inheritance
7.6 Summary
2
7.1 Introduction
In C++, the concept of Reusability is promoted by the mechanism of inheritance. Inheritance is the
most important feature of C++ in which the new classes are created from the existing one by
inheriting all the properties of previous class and also adding new members which are not available
in the parent class. The mechanism of deriving a new class from an old class is inheritance. The new
class is called derived class or subclass and the old class is called base class or superclass. A class
can be derived from more than one base class and more than one new classes can be derived from a
base class. Also a new class can be derived from another derived class. On the basis of mechanism
of derivation, the inheritance may be of different types like Single Inheritance, Multiple Inheritance,
Hierarchical Inheritance, Multilevel Inheritance and Hybrid Inheritance. All of these are explained in
next sections.
7.1 Objectives
7.2 Inheritance
Inheritance allows one class to reuse the state and behaviour of another class. It is a mechanism to
create new class i.e. derived class from the other existing class called Base class. The derived classes
3
have more members than that of base class. The derived class contains properties of base class and
few of its own. The object of derived class can access not only its own members but also the
members of the base class. However, the object of the base class cannot access the members of
derived class.
A subclass (or derived class) can be inherited from a superclass (or base class).
......
};
The colon shows that the derived class is derived from the base class. The access specifiers
may be private, public or protected. The access specifier is optional. By default access specifier is
private.
The access specifiers decide whether the characteristics of the base class are derived privately or
publicly. C++ supports three access specifiers: private, public and protected.
I. When a public specifier is used, the public members of the base class are public to the
derived class and protected members of the base class are protected to the derived class.
For example:
4
# include < iostream.h>
class BS
int x = 15;
public:
void showx( )
};
class DR : public BS
int y = 30;
public:
void showy( )
};
void main ( )
5
clrscr ( );
DR d;
d . showx ( );
d. showy ( );
OUTPUT
Here class DR is publically derived from class BS. Therefore the object d of derived
class DR can access the public member of base class BS as well as derived class DR.
II. When a private specifier is used, the public and protected members of the base class are
For example:
class BS
int x = 15;
public:
void showx( )
6
{
};
class Dr : private Bs
int y = 30;
public:
void showy( )
showx ( );
};
void main ( )
clrscr ( );
Dr d;
d. showy ( );
7
OUTPUT
Here class DR is privately derived from class BS. Therefore the object d of derived
class DR cannot access the public member of base class BS directly. It can only access
the public members of derived class DR. Here d. showx ( ) won’t work.
III. When a derived class is inherited as protected, then all public members of the base class
will become protected and protected members will remain protected in the derived
class.
For example:
class BS
protected:
int x = 15;
public:
void showx( )
8
};
class DR : protected BS
int y = 30;
public:
void showy( )
};
void main ( )
clrscr ( );
DR d;
d. showy ( );
OUTPUT
9
Here class DR is protectedly derived from class BS. Therefore the object d of derived
class DR cannot access the public member of base class BS directly. It can only access
the public members of derived class DR. Here d. showx ( ) won’t work. The main thing
is that protected members of base class are shown as protected members of derived
class and therefore public members of derived class can use protected members of base
class directly.
Access specifiers with their scopes are shown in the table 7.1 given below:
The process of inheritance may be a simple one or complex. This depends on the following points:
10
Mechanism of derivation
I. Single Inheritance
V. Hybrid Inheritance
Single inheritance involves only one base class and one derived class. Only one subclass is inherited
from a single base class as shown in figure 7.1. The derived class could not be used as base class
further.
Base Class
(Employee)
Derived Class
(Salary)
11
# include < iostream.h>
class Employee
protected:
int Emp_id;
};
float Amt;
public:
Emp_id = e;
Amt = s;
void show_salary ( )
};
void main ( )
12
clrscr ( );
Salary s1;
s1. show_salary ( );
OUTPUT
In this program, the two classes Employee and Salary are declared. The class Salary is derived from
the base class Employee. The base class Employee has a protected member Emp_id and the derived
class Salary has a data member Amt showing salary of the employee. As class Salary is publically
inherited, therefore protected data of base class i.e. Employee class can be shown as protected data
in derived i.e. Salary class. The object s1 of derived class (Salary) invokes member functions
In this type of inheritance a class is derived from another derived class. It means a derived class also
acts as a base class for another derived class which is also called intermediate base class. The classes
13
…………
};
class < Class Name 2> : <access specifier> < Class Name1>
…………..
};
class < Class Name 3> : <access specifier> < Class Name2>
…………..
};
The figure 7.2(a) and 7.2(b) illustrates the multilevel inheritance with simple examples.
Base Class
(Grand father)
Intermediate
Base Class
(Father)
Derived Class
(Child)
14
Base Class
(Shape)
Intermediate
Base Class
(Ellipse)
Derived Class
(Circle)
class Shape
protected:
char sname[25];
public:
void get_ShapeName ( )
15
cin>> sname;
void show_ShapeName( )
};
protected:
public:
Ra = a;
Rb = b;
void show_ElpArea ( )
16
};
public:
void show_CrArea ( )
};
void main ( )
clrscr ( );
Shape S1;
S1. get_ShapeName ( );
S1. get_Radius ( 6 );
S1. show_CrArea ( );
OUTPUT
Circle
17
Area of Circle : 113.112
In this program, three classes Shape, Ellipse and Circle are defined. The class Shape gets and shows
the shape name. The class Ellipse is derived from the class Shape and stores both the major axis and
minor axis radius by calling the function getRadius ( ). The show_ElpArea ( ) function displays the
area of ellipse. The function getRadius ( ) also takes one default argument so that it can be used for
class Circle which is derived from class Ellipse. The function show_CrArea ( ) in the class circle
calculates the area of circle by using the protected members Area and Ra of class Ellipse. The class
Circle inherits the details of class Shape and class Ellipse by using multilevel inheritance.
In multiple inheritance a derived class can be inherited from two or more than two base classes. The
derived class contains the features of all the base classes. It is like a child that inherits the features of
class < Derived> : < access specifier> < Base1>,< access specifier> < Base2> …..
……………………
……………………
……………………
};
18
Examples of multiple inheritance are shown in figure 7.3(a) and figure 7.3(b).
Derived Class
(Child)
Derived Class
(Orange)
19
A program showing multiple inheritance is shown below. In this program two base classes Red and
Yellow are inherited by the derived class Orange. The output shows the names of colours and
class Red
public:
void Red ( )
};
class Yellow
public:
void Yellow ( )
};
20
class Orange: public Red, public Yellow
public:
void Orange ( )
};
void main ( )
clrscr ( );
Orange O1;
OUTPUT
In this program, object of derived class Orange is declared. When object is declared constructors are
This type of inheritance defines a hierarchy where certain features of one level are shared by many
others below that level. It means the inheritance where two or more classes are derived from a single
21
base class is called Hierarchical Inheritance. Figure 7.4 shows hierarchical inheritance in which class
Account is base class and SavingAccount, CurrentAccount & FixedDeposit are three derived classes.
Base Class
(Account)
Let us take an example of hierarchical inheritance with a base class Account and three derived
class Account
protected:
22
char name[25 ] ;
public:
void get_name ( )
cin>> name;
void show_name ( )
};
int Acc_no;
float Amount ;
public:
get_name( );
Acc_no = a;
Amount = b;
23
}
void show_data ( )
show_name ( );
};
int Acc_no;
float Amount ;
public:
get_name( );
Acc_no = a;
Amount = b;
void show_data ( )
24
show_name ( );
};
int Acc_no;
float Amount ;
public:
get_name( );
Acc_no = a;
Amount = b;
void show_data ( )
show_name ( );
};
25
void main ( )
clrscr ( );
Saving_Account s1;
Current_Account c1;
Fixed_Account f1;
s1. show_data( );
c1. show_data( );
f1. show_data( );
OUTPUT
Name : Ram
Name : sham
Name : tom
26
In the above program, the objects of derived classes are declared and base class data is accessed by
the member functions of derived classes which are further accessed by the objects of the derived
classes.
Hybrid inheritance is the combination of two or more types of inheritances such as single
hybrid inheritance are shown in figure 7.5(a) and 7.5(b). In figure 7.5(a) a class Area inherits the
properties of two base classes Length and Breadth and class Volume is derived from intermediate
Derived Class
(Volume)
27
Let us take a program to implement the above example.
class Length
float len ;
public:
float get_Length ( )
cin>> len;
return len;
};
class Breadth
float bd ;
public:
float get_Breadth( )
28
cin>> bd;
return bd;
};
protected:
float Area ;
public:
void Area ( )
void show_Area ( )
};
class Height
float ht;
public:
29
float get_Height( )
cin>> ht;
return ht;
};
float Vol ;
public:
void display_Volume ( )
};
void main ( )
clrscr ( );
Volume V1;
V1. display_Volume ( );
30
OUTPUT
Volume : 210
In the above program, class Area is publically inherited to base class Length and base class Breadth.
Also Class Volume is publically inherited to class Area and another base class Height. In main ( )
function when object V1 of class Volume is created, the constructor function of class area is
executed, which calls the public member functions get_Length ( ) of class Length & get_Breadth ( )
of class Breadth and calculates the area. The statement V1. display_Volume ( ) calls the public
member function display_Volume ( ) of class Volume which in turn uses the protected data member
Area of class Area and public member function get_Height ( ) of class Height to calculate the
volume.
In figure 7.5(b) another example of hybrid inheritance is shown in which class Test is derived from
base class Student and then class Result is derived from class Cultural, class Test and class Sports. It
means the result of a student includes the test as well as cultural and sports activities. This example
31
Base Class 1
(Student)
Derived Class
(Result)
The program given below shows hybrid inheritance by implementing the above example.
class Student
protected:
int Rollno ;
public:
32
void get_no ( )
cin>> Rollno;
void show_no ( )
};
protected:
public:
marks1 = a;
marks2 = b;
void show_marks ( )
33
cout << “\n marks in subject 1 :” << marks1 ;
};
class Sports
Protected:
float s_score ;
public:
s_score = s;
void show_sscore( )
};
class Cultural
protected:
float c_score ;
34
public:
c_score = c;
void show_cscore( )
};
float total ;
public:
void display_result ( )
show_no ( );
show_marks ( );
show_sscore( );
show_cscore( );
35
};
void main ( )
clrscr ( );
Result st1;
st1. get_no ( );
st1. get_sscore(6);
st1. get_cscore(7);
st1. display_result ( );
OUTPUT
12
Rollno 12
sports wt: 6
cultural wt: 7
36
In the above program, the object of class Result is declared. The class Result is derived publically by
the classes Test, Sports and Cultural. The member functions of all these classes are accessed by the
The constructors and destructors are the member functions having same name as that of class in
which they are defined. Basically the constructors are used to initialize the variables of object and
destructors are used to destroy the object. In case of inheritance the derived class need not have a
constructor if base class constructor takes no arguments. But if the base class constructor takes one
or more arguments then the derived class must have a constructor because the derived class
constructor passes arguments to the base class constructor. When an object of derived class is
declared, firstly the base constructor is executed and then derived class constructor is executed.
In case of more than one base classes, the base class constructors are executed in order in which they
appear in the declaration of the derived class. Also in multilevel inheritance, the constructors are
executed in the order of inheritance. Similarly, the destructors are executed in reverse order of
constructor’s execution. Let us take an example to show the sequence of execution of constructors
and destructors.
37
public:
X()
~X ( )
};
public:
Y()
~Y ( )
};
38
{
public:
Z()
~Z ( )
};
void main ( )
clrscr ( );
OUTPUT
39
destructor of base class X
In the above program two base classes X and Y are defined with constructors and destructors. Z is
the third class derived from the both base classes and its object is declared. As the output describes
firstly constructor of base class X is executed then that of base class Y because base class X is first
in order in the declaration of derived class. In the last the derived class constructor is executed. The
7.6 Summary
The new class is called derived class or subclass and the old class is called base class or
superclass.
The object of derived class can access not only its own members but also the members of the
base class.
The access specifiers decide whether the characteristics of the base class are derived
privately or publicly.
In single inheritance, only one subclass is inherited from a single base class.
A derived class is inherited from two or more than two base classes in multiple inheritance.
40
The inheritance where two or more classes are derived from a single base class is called
hierarchical inheritance.
In inheritance the execution of constructors takes place from base class to derived class.
The destructors are executed in reverse order that is from derived class to base class.
Object Oriented Programming With Ansi & Turbo C++ By Ashok N. Kamthane, Pearson
Education.
5. What is difference between single and multilevel inheritance? Explain with an example.
6. What is the difference between multiple and multilevel inheritance? Explain with an
41
example.
10. Write a program to show the order of execution of constructors and destructors in
inheritance.
11. Write a program to calculate the Income tax of employees of a firm by using the current
12. Write a program to find out the interest on the amount deposited by the customers in the
13. Write a program to calculate the bill for electricity. Read the initial and final reading for the
14. Write a program to make a list of staff members of a college and arrange them in order of
42
UNIT – IV
Different Forms of Inheritance – Single, Multiple, Multilevel, Hierarchical and Multipath Inheritance
Roles of Constructors and Destructors in Inheritance.
KURUKSHETRA UNIVERSITY,
KURUKSHETRA-136119
BCA III
Lesson No. 08
8.1 Introduction
8.2 Objectives
1
8.5.1 Exception Handling Mechanism
8.6 Summary
2
8.1 Introduction
Generic programming is an approach which handles a variety of data types by using generic data
types as arguments. The goal of generic programming is to write code that is independent of
the data types. A function that works for all C++ data types is called as generic function. A template
is one of the most useful features in C++ which provides supports for generic programming.
Template allows a single function or class to work with different data types. When used with classes
they are called class templates and when used with functions they are called function templates. A
template is defined with parameters that would be replaced by the specified data types at the time of
actual use of the class and functions. They can accept data of any type used in C++. Thus many
functions accepting different data types are replaced by a single function that can accept different
data types.
Another important and advance feature of C++ is Exception Handling. Exceptions are run time
errors that a program may encounter during execution like division by zero or running out of the
memory. Exception handling provides an integrated technique to tackle with these run time
problems. The main goal of exception handling is to provide means to detect and report exceptions
in order to take proper action. Let us discuss both the concepts in detail.
8.1 Objectives
3
Describe the implementation of Exception handling mechanism to handle run time errors.
The templates used with classes are called class templates. The class template creates a generic class
with an anonymous type. The data members of the class can be declared as of template type and the
member functions can also use them. No separate declaration is used for defining member function
………………………………
};
Here template and class are keywords. ‘T’ is a variable of template type that must be declared
with in < > (angle brackets). ‘T’ is used in the class to define variables of template type. Templates
cannot be declared inside the class or functions. They must be global. The following example
class Number
4
public:
Number ( T value )
};
void main ( )
clrscr( );
OUTPUT
Entered Number is 35
Entered Number is N
Here three values of different data types are printed by using single constructor function with the
help of templates.
The main advantages of using templates are that it decreases the source code and hence require less
time. Also as the program size is decreased, it occupies less disk space.
5
8.2.1 Class Templates with Multiple Parameters
The classes using templates are generic type and member functions of these classes can operate on
different data types. The class template may contain one or more parameters of generic data type.
The arguments are separated by comma in template declaration. The syntax is as under:
class Class_Name
………….
………….
};
Two arguments of generic type T1 and T2 known as template arguments can be used by the member
functions of the class. The following program provides the largest number out of the two numbers of
class Largest
T1 Val1;
T2 Val2;
public:
6
Largest ( T1 x, T2 y )
Val1 = x;
Val2 = y;
void Show_result( )
};
void main ( )
clrscr( );
L1. Show_result ( );
L2. Show_result ( );
L3. Show_result ( );
OUTPUT
Larger value is P
7
Larger value is 65.05
In the above program, two data members (i.e. Val1 and Val2) of template data type T1 & T2 are
declared and the member function Show_result ( ) displays the larger number out of the two.
Similar to class templates, function templates can be defined to create a number of functions with
………………..
// Function body
The syntax is similar to the syntax of class template. The main difference is that functions are
defined here rather than classes. They are not member functions of any class and hence can be
invoked directly without using object and dot operator. The template type T can be used in argument
list as well as in the body of function. Template functions mainly deal with four data types i.e. int,
Let us reconsider the previous example of class template and elaborate it with function templates.
8
template < class T>
Number ( T value )
void main ( )
clrscr( );
Number (35);
Number (‘N’);
Number (65.05);
OUTPUT
Entered Number is 35
Entered Number is N
Here the function Number ( ) has one argument ‘value’ of template type T and it is used to display
Functions can use arguments of more than one template type by declaring more than one generic
9
template < class T1, class T2, …….. >
………………..
// Function body
void main ( )
clrscr( );
10
}
OUTPUT
We can define the member functions outside the class. However, these member functions must be
defined by the function templates because member functions of the template classes themselves are
parameterized by the type argument of template class. The general syntax is as under:
…………….
// function body
……………..
11
template < class T>
class Number
public:
Number ( T value );
};
void main ( )
clrscr( );
OUTPUT
Entered Number is 35
Entered Number is N
12
In the above program, the constructor function Number ( ) is defined outside the class.
Exception handling is a mechanism that provides resources to identify and report an exceptional
circumstance in order to take proper action. The error handling code performs the following tasks:
Exception handling mechanism as shown in figure 8.1 is basically built upon three keywords:
i. try: The keyword try is the name of block that encapsulates the statements which may
ii. throw: When an exception is identified, it is thrown by using a statement throw. The throw
iii. catch: the keyword catch defines the catch block which catches and handles the exception
13
try block
Exception object
catch block
When try block passes an exception using throw statement, the control of the program is passed to
the catch block. The catch block must immediately follow the try block that throws the exception.
Also remember that the data types used by the throw and catch statements must be same. If they do
not match the program is aborted with the help of function abort ( ) which is invoked by the compiler
by default. When no error has occurred and no exception is thrown, then the catch block is ignored
and the statement after the catch block is executed. The point at which the throw is executed is called
throw point. Once an exception is thrown to the catch block, control cannot return back to the throw
point.
14
Statement;
try
{ …………………
…………………
…………………
…………………
…………………
…………………
……………………………..
int main ( )
int m,n;
15
cout << “ enter the values\n”;
cin>> m;
cin>> n;
try
if ( n != 0)
else
return 0;
OUTPUT
16
45 0
Exception handled; n = 0
The above program detects and catches a division-by-zero problem. The exception is thrown by
using an object x of int type. As the data type of exception object is int, therefore catch statement
If a program has more than one condition to throw an exception, then multiple catch blocks with a
single try block are used. The format of multiple catch statements are as follows:
try
// try block
// catch block 1
// catch block2
………………….
17
………………….
// catch block 1
When an exception is thrown, the catch blocks are searched in order. The very first catch block that
yields a match is executed. After executing the catch block, the control goes to the first statement
try
else
else
18
catch (char ch)
catch ( int m)
catch ( double d)
void main ( )
clrscr ( );
Number ( 7 );
Number ( 0);
Number ( -2 );
OUTPUT
19
end of try-catch block
In the above program, the function Number ( ) is first invoked with positive number 7 and throws an
int exception. After that the function is again invoked with 0 and throws an character exception and
in the last it is invoked with negative value -2 and throws an exception of double type.
It is possible to define a single catch block to handle all possible types of exceptions. In such
catch ( …. )
20
{
try
else
else
catch (……)
void main ( )
clrscr ( );
Number ( 7 );
Number ( 0);
Number ( -2 );
21
OUTPUT
caught an exception
caught an exception
caught an exception
The above program is same as the previous one. The difference is that rather than using multiple
Sometimes an exception received by the catch block is passed again to another exception handler.
throw ;
For example:
try
if ( y = = 0)
22
throw y; // int
else
catch ( int y)
Throw;
int main ( )
try
Division ( 20 , 0 );
23
cout<< “ End of main ( ) function\n”;
return 0;
OUTPUT
inside main
inside function
In the above program the catch block inside the function accepts the exception and throws again
We can restrict a function to throw only certain specified exceptions outside of it. This is
accomplished by adding a throw list clause to the function definition. The general form of this as
shown here:
………………….
…………………
24
}
The type-list specifies the type of exceptions that may be thrown. Throwing an exception that is not
supported by the function causes abnormal program termination. We can restrict a function from
else
else
int main ( )
try
Number (0);
25
catch (char ch)
catch ( int m)
catch ( double d)
return 0;
OUTPUT
In the above program the function Number ( ) may only throw integer, character and double
exceptions. If any other type of exception is tried to throw, an abnormal program termination will
occur.
26
8.6 Summary
A template is one of the most useful features in C++ which implements the concept of
generic programming.
Template allows a single function or class to work with different data types.
The main advantages of using templates are that it decreases the source code and hence
Function templates can be invoked directly without using object and dot operator.
Template functions mainly deal with four data types i.e. int, char, float and double.
Exceptions are run time errors that a program may encounter during execution like division
Exception handling mechanism is basically built upon three keywords: try, throw and catch.
The data types used by the throw and catch statements must be same.
If a program has more than one condition to throw an exception, then multiple catch blocks
are used.
A single catch block can also be used to handle all possible types of exceptions.
It is possible to restrict a function to throw only certain specified exceptions outside of it.
27
8.7 Suggested Readings
Object Oriented Programming With Ansi & Turbo C++ By Ashok N. Kamthane, Pearson
Education.
3. What is the difference between class templates and function templates? Explain with an
example.
4. How can normal function be declared as template function? Explain with an example.
5. How can member function be declared as template function outside the class? Explain with an
example.
28
10. Describe the role of try, throw and catch keywords in exception handling.
12. How are multiple catch blocks defined? Explain with an example.
13. Explain the procedure for restricting certain types of exceptions with suitable example.
14. Write a program to create a template to find the maximum and minimum value stored in an
array.
15. Write a program to find the reverse of given number and string using template functions.
16. Write a program to convert the decimal number into binary number using templates.
17. Write a program to accept a string. If any space is encountered then throw exception.
18. Write a program to implement stack. Use exception handling if overflow or underflow exist.
19. Write a program to accept 10 integers in an array. If any negative number or zero is found then
throw exception.
21. Write a program to accept a number and find out the factorial of given number. Use exception
handling.
29
UNIT – IV
Different Forms of Inheritance – Single, Multiple, Multilevel, Hierarchical and Multipath Inheritance
Roles of Constructors and Destructors in Inheritance.
KURUKSHETRA UNIVERSITY,
KURUKSHETRA-136119
BCA III
Lesson no. 09
9.1 Introduction
9.2 Objectives
9.5.2 Manipulators
1
9.6.1 Basic Type Conversion
9.7 Summary
2
9.1 Introduction
Every program or application needs some input data and generates results after processing the input
data. Therefore, it is necessary to know how to provide input data to an application and how to
format the output data in the desired form. C++ supports a large set of I/O functions and operators
to do this. C++ also supports all the I/O functions of C but Programmers restrained from using them
as I/O methods in C do not support object oriented features. C++ uses the concept of stream classes
to perform I/O functions with console and disk files. All the console I/O functions and operators are
C++ supports various basic (built-in) data types such as integer, character, float, double as well as
user-defined data types (class type). Type conversions are necessary if an expression contains
operands of different data types. Type conversions may be implicit (carried out by the compiler
itself automatically) or explicit in which the compiler is instructed to do the conversion either by
typecast operator or by some conversion routines. When constants and variables of different built-in
data types are included in the expression, automatic type conversions are performed or it may be
done explicitly by using typecast operator. But in case of user-defined data types compiler does not
support the automatic type conversions therefore some conversion routines are necessary. All these
9.2 Objectives
Describe the unformatted I/O operations for input data and output the results.
3
Describe the formatted I/O operations for input data and format the results.
Describe type conversions from basic data types to user-defined data types and vice-
versa.
A stream is an interface to the programmer provided by the I/O system. It is a sequence of bytes. It
acts either as a source from which input data can be obtained or as a destination to which output
data can be sent. The source stream that provides data to the program is called input stream and the
destination stream that receives data from the program is known as output stream. The data in the
input stream can be takes from any input device like keyboard or any other storage device whereas
the data in the output stream can go to the screen or storage device. The cin and cout are the
The C++ contains a hierarchy of classes that are used to define various streams to deal with both
console and disk files and these classes are known as stream classes. All these classes are declared
in the header file ‘iostream.h’ which should be included in all the programs to communicate with
the console unit. The hierarchy of stream classes used for input and output operations with the
4
ios
iostream
Here ios is the virtual base class and provides basic support for formatted & unformatted I/O
operations. The classes istream and ostream are derived from ios and act as base classes for the
iostream. The class istream( i.e. input stream) inherits the properties of ios class and provides the
facilities for both formatted and unformatted input. Similarly the class ostream (i.e. output stream)
inherits the properties of ios class and provides the facilities for both formatted and unformatted
ouput. The class iostream inherits the properties of ios, istream and ostream classes through
multiple inheritance and contains all the I/O functions. Three classes istream_withassign,
5
ostream_withassign and iosream_withassign are derived from istream, ostream and iostream classes
respectively and add assignment operators to these classes. The class streambuf provides an
Unformatted I/O functions accept and display the data without any formatting. Data is handled by
the I/O functions with default setting and users need not to apply any external setting. Such data is
called unformatted data. The operators and functions that perform unformatted operations are as
follows:
The cin object (predefined in the iostream file) reads the data from the input device by
overloading the extraction operator >> in the istream class. Its syntax is as follows:
Variable1, Variable2, …….. are variable names that have been declared already in the
program.
The input data should be separated by white spaces because the reading for a variable is
terminated at the encounter of a white space or a character that does not match the
6
destination type. The data should match the type of variable in the cin list. Let us take an
example.
int Number;
Suppose the input data is 3442. The cin accepts 3442 and assigns the value 3442 to the
Number. Let us further consider the input data is 3442A. In this case also, the cin assigns
Similarly the cout object (predefined in the iostream file) displays the data on the output
device by overloading the insertion operator << in the ostream class. Its syntax is as
follows:
Variable1, Variable2, …….. are variable names that have been declared already in the
program.
The above statement displays the contents of Variable1, Variable2, ……… on the screen.
The cout also displays the message on the screen by the syntax as follows:
For example
The output is
7
II. get ( ) and put ( ) Functions
The get ( ) function (a member of istream) is used to read a single character including the
blank space, tab and the newline character and invoked by the object cin.There are two types
of get ( ) function:
For example
char ch;
The put ( ) function (a member of ostream) is used to display a character and invoked by the
object cout.
For example
Let us take a program to read and display a line of text using get ( ) and put ( ) functions.
void main ( )
clrscr ( );
8
char ch ;
ch = cin.get ( );
while( ch != ‘\n’)
cout.put ( ch );
cin.get (ch );
INPUT
OUTPUT
The getline ( ) function is used to read a whole line of text that ends with a newline
This reads the text until the newline character is encountered or the size minus 1 (size – 1)
characters are read (whichever occurs first). The newline character is replaced by the null
character.
For example:
9
char Text[15];
The input will be terminated after reading 14 characters and the output will be
Good Morning I
The write function displays the whole line and also invoked by the cout object. Its syntax is
The first argument represents the name of string to be displayed and the second argument
For example:
gives output
Morni
Similarly
cout. write(“Hello”,6);
cout.write (“India”,5);
gives output
Hello India
Here the first statement displays “Hello” followed by the blank space because the argument
value is greater by one than the actual string length. The last statement shows “India”. In
this statement the argument value and string length are same and therefore no blank spaces
10
Let us take a program to read and display a string using getline ( ) and write ( ) functions.
void main ( )
clrscr ( );
char ch [25] ;
INPUT
OUTPUT
Formatted I/O functions accept and display the results after formatting the output. Such data is
called formatted data. C++ supports a number of formatted I/O functions that could be used for
11
formatting the data. The various format setting like number format, field width, precision,
justification, scientific notation etc. can be performed on the data by the formatted I/O functions.
ii. Manipulators
The ios class provides a large number of operations to both input and output. Some important
functions that format the output are listed in table 9.1. The table also describes the meaning of each
Function Description
width ( ) Specify the required field size for displaying the output.
precision ( ) Specify the number of digits after the decimal point of a float value.
setf ( ) Specify various format flags that can control the form of output to be
displayed.
12
The detailed description of ios class functions are as follow:
I. width( ) Function
The width ( ) function is used to define the width of a field required for displaying the value
/output of an element. The data value shown in the field is right justified by default.
cout. width ( w );
it sets the field width ‘ w ’ for an item and also returns the previous width setting. Its return
type is integer and also takes argument of integer type. The function without argument
returns the current width setting. After printing one element field, width revert back to the
default settings.
void main ( )
clrscr ( );
int x;
cout.width ( 6 );
cout<< “ RAM”;
cout.width ( 4 );
13
cout<< 23 << “\n”;
x = cout.width ( 1 );
OUTPUT
R A M 2 3
In the above program “RAM” and 23 are displayed as per the field setting and the value of x
The value (whether text or number) is printed right-justified in the field width created. Also
remember that if the size of the value to be displayed is larger than the specified field width
The precision ( ) function specify the number of digits after the decimal point of a floating
point number. By default the floating point numbers are printed with six digits after the
decimal point. The function is also invoked by the object cout as follows:
14
cout. precision ( n );
It sets the n number of digits to the right of decimal point and also returns the previous
precision number. We need not to set the precision for each number. Once specified, it
retains the precision value in effect until it is reset. To print the current precision setting, the
void main ( )
clrscr ( );
int x;
cout.precision ( 4 );
x = cout.precision ( );
15
OUTPUT
5.4448
23.0056
The fill ( ) function is used to fill the unused spaces of a field by the specified character. Its
return type is char and it also takes argument of char data type.
The syntax is
cout.fill ( ch );
where ch is the character used to fill the unused positions. The function without argument
returns the character currently used for filling the unused positions. Also note that the
character ‘ \ ’ is not allowed for used with fill( ) function to fill the blank spaces because it is
void main ( )
clrscr ( );
char x;
16
cout.fill( ‘#’);
cout.width ( 6 );
cout<< “ RAM”<<”\n”;
x = cout.fill ( );
OUTPUT
# # # R A M
Padding character = #
The setf( ) function stands for set flags. This function is used in C++ for setting the flags to
where arg1 is the name of formatting flag defined in the ios class and specifies the format
action required for the output. Another argument arg2 also belongs to ios class known as bit
field and specifies the group to which the formatting flag belongs. Table 9.2 shows the
17
S. No. Formatting Bit Field(arg2) Formatting Output
Flag(arg1)
void main ( )
clrscr ( );
cout.fill( ‘#’);
cout.width ( 6 );
cout<< “ RAM”<<”\n”;
18
}
OUTPUT
R A M # # #
Some flags do not have bit fields and therefore they are used as single argument in setf ( )
function.
For example
display the value with trailing decimal point and trailing zeros when the data element is
The table 9.3 shows the list of flags and their actions that do not have bit fields.
Table 9.3 Flags and their actions that do not have bit fields
19
V. unsetf ( ) Function
The unsetf ( ) function is used to clear the formatting flags. The syntax is as under:
For example:
clears the ios: : left flag and after this statement data is printed with default setting i.e. right-
justified.
9.5.2 Manipulators
Manipulators are special functions which can be used to manipulate the output format. These
functions are defined in header file iomanip.h and provide the same features as that of the ios
For example
20
S. No. Manipulators Description Equivalent ios
functions
precision to n.
Users can create their own manipulators for some special purposes. The general syntax for creating
………………. // code
……………….
………………..
return output;
21
Here Manipulator _Name is the name of manipulator to be created.
return output;
void main ( )
clrscr ( );
OUTPUT
RAM
SHAM
In the above program the user defined manipulator ‘line’ is defined. Whenever ‘line’ is used in
program the ‘\n’ is executed and a new line is inserted in the output.
Let us take another program to create a manipulator ‘tab’ equivalent to escape sequence ‘\t’.
22
#include < iostream.h >
return output;
void main ( )
clrscr ( );
OUTPUT
RAM SHAM
In this program a manipulator ‘tab’ is created which contains the definition of escape sequence ‘\t’.
Whenever we use ‘tab’ in the program, the ‘\t’ is executed which is shown in the output.
Type conversion is the process of converting the value of variables in an expression from one type
to another type in order to evaluate the expression without errors. C++ permits type conversions
23
whenever data types are mixed in an expression. If the data types are built-in, type conversions are
performed automatically by the compiler itself (implicit) or it can be done explicitly by typecast
operator. But the compiler has no idea about the user-defined data types as they are designed by us
to suit our requirements. Therefore different conversion routines are required to perform such
operations. Following are the different situations of the type conversions which are explained in
next sections.
C++ allows implicit as well as explicit type conversions when various basic built-in data types are
a) Implicit Type Conversion: Implicit type conversion (also called Automatic Type
type is expected, but a different fundamental data type is supplied, and the user does not
explicitly tell the compiler how to perform this conversion (via a cast). There are two basic
types of implicit type conversion: promotions and conversions. Whenever a value from one
smaller data type is converted into a value of a larger similar data type, this is called
24
a numeric promotion (or widening). The promotions are always safe, and no data loss will
When we convert a value from a larger type to a smaller type, or between different types,
Conversions may or may not result in a loss of data. Because of this, any code that does an
When evaluating expressions, the compiler breaks each expression down into individual sub
expressions. The arithmetic operators require their operands to be of the same type. If
operands of mixed types are used, the compiler will implicitly convert one operand to agree
with the other using a process called arithmetic conversion. For example in a binary
operation, if one of the operand is of int data type and the other is of float, the int is
converted into a float. Some resulting data type of different mixed mode operations are
25
Operand 1 Operand 2 Resulting Data type
b) Explicit Type Conversion: C++ allows explicit type conversions where the programmer
uses a typecast operator to direct the conversion. It is always preferred to use explicit type
int x = 20;
int y = 6;
float f = x / y;
Here Variable f will result with the value of 3. How does the compiler know that we want to
use floating point division instead of integer division? The answer is by using a type casting
operator to tell the compiler to do explicit type conversion. A typecast represents an explicit
26
request by the programmer to do a type conversion. The typecasting is done via the ( )
Here, the resulting value of f is 3.333333. Because a float cast is used to tell the compiler to
promote x to a floating point value. Because x is a floating point value, y will then be
promoted to a floating point value as well, and the division will be done using floating point
division instead of integer division. Also it is noted that C-style casts should generally be
avoided.
The conversion from basic to class type is easily accomplished with the help of constructors.
Constructors are not only used to initialize the objects but they also perform type conversion from
the argument type to the constructor’s class type. Consider an example of converting a int type
class Time
27
int hours;
int minutes;
public:
Time( int t )
hours = t/60;
minutes = t % 60;
void show ( )
};
void main ( )
T1 = Time(period1);
T2 = period2;
T1.show ( );
T2.show ( );
28
OUTPUT
1 hours 35 minutes
1 hours 15 minutes
T1 = Time(period1);
first convert period1 from integer type to class type and then assign the class type values to the
object T1.
The statement
T2 = period2;
The example shows that the constructor used for the type conversion always take a single argument
whose type is to be converted. Also the left hand operand of = operator is always a class type object
and right side operand is always of basic type variable. Therefore this conversion can also be
C++ permits to define an overloaded casting operator that could be used to convert a class type data
to basic type. The casing operator function should satisfy the following conditions:
29
Operator < type_name > ( )
……………
……………
The function converts a class type data to type_name. Consider the following conversion function
operator double ( ) to find the magnitude of a vector which converts the class type (vector) object to
double.
double sum = 0 ;
or
where V1 is the object of vector class. Also the values used by the function belong to the object of
the class that invoked the function. It implies that the function does not need an argument. Let us
consider another example to convert class type data to basic type data:
30
# include < conio.h >
class data
int x;
float y;
public:
data( )
x = 5;
y = 6.5;
operator int ( )
return ( x );
operator float ( )
return ( y );
};
void main ( )
31
data D;
int a;
float b;
OUTPUT
value of a : 5
value of b : 6.5
Here the class type data is the combination of two basic data types integer and float. The statements
a = D;
b = D;
converts the class type data to the integer type and float type respectively.
When an object of one class is assigned to the object of another class, it should be necessary to
convert the type of right hand side object to the type of left hand side object.
For example:
32
Here objA is the object of class A and objB is the object of class B. The class B type data is firstly
converted to the class A type data and the converted value is assigned to the objA. Since the
conversion takes place from class B to the class A, class B is known as source class and the class A
is known as destination class. There are two methods to convert one class type to another class type,
The casting operator function is located in the class which needs to be converted i.e. source class.
The conversion takes place in the source class and the result is given to the destination class as
Class B (Source)
Casting operator
Function
Converted value of type A
Conversion takes place here
Figure 9.2 Conversion between class types using casting operator function
Another method i.e. one argument constructor function must be defined in the destination class. It
converts the argument’s type to the type of class of which it is a member (destination class) which
implies that the argument belongs to the source class and is passed to the destination class for
conversion.
Figure 9.3 Conversion between class types using one argument constructor
33
Let us consider an example of converting three integers for date, month & year into date format by
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
char dt[12];
public:
Date( )
dt[0] = NULL;
void display( )
cout<< dt;
int dy = p.day ( );
int yr = p.year ( );
34
char tmp[5];
itoa(dy,dt,10);
strcat(dt, “-”);
itoa(mth,tmp,10);
strcat(dt,tmp);
strcat(dt, “-”);
itoa(yr,tmp,10);
strcat(dt,tmp);
};
public:
dy = d;
mth = m;
yr = y;
int day ( )
return ( dy );
35
}
int month ( )
return ( mth );
int year ( )
return ( yr );
void display ( )
};
void main ( )
clrscr( );
Date D2;
D2 = D1;
D1.display( );
cout<< “\n D2 = ”;
36
D2.display ( );
};
OUTPUT
D1 = 1 1 2016
D2 = 1-1-2016
Here D1 is the object of DMY (source) class and D2 is the object of DT (destination class). As the
statement D1 = D2 is executed, the one argument constructor defined in the class Date is invoked
and conversion takes place. Also function itoa ( ) used in the constructor converts the int data value
into string.
Similarly, casting operator function can be used to perform this conversion in the class DMY to
9.7 Summary
The I/O system of C++ provides an interface to the programmer called stream.
A stream is a sequence of bytes. It acts either as a source (input stream) from which
input data can be obtained or as a destination (output stream) to which output data can
be sent.
The C++ contains a hierarchy of classes that are used to define various streams to deal
with both console and disk files and these classes are known as stream classes.
All the stream classes are declared in the header file ‘iostream.h’.
37
C++ provides two types of I/O functions: (i) Formatted I/O functions and (ii)
>> (Extraction operator), << (Insertion operator), get ( ), put ( ), getline ( ) and write ( )
The formatted functions include ios class functions, manipulators and user-defined
manipulators.
The manipulators are special functions which can be used to manipulate the output
format.
They provide the same features as that of the ios functions and flags.
Implicit type conversion (also called Automatic Type Conversion) is performed by the
compiler automatically whenever one fundamental data type is expected, but a different
In explicit type conversions, the programmer uses a typecast operator to direct the
conversion.
But the compiler has no idea about the user-defined data types. Therefore different
conversion routines are required to perform conversions between the user-defined data
types.
The conversion from basic to class type is accomplished by the use of one argument
38
constructor.
An overloaded casting operator is used to convert a class type data to basic type.
The conversion of one class type to another class type is performed either type
Object Oriented Programming With Ansi & Turbo C++ By Ashok N. Kamthane, Pearson
Education.
39
6. What is the role of extraction operator and insertion operator in I/O system? Discuss
with examples.
8. What is the difference between get ( ) and getline ( ) functions? Explain with an
example.
11. List the formatting flags that do not have bit fields.
13. What do mean by typecasting? Explain the difference between implicit and explicit
typecasting.
15. Define casting operator or conversion function. Explain its syntax. What are the
16. Explain the conversion of data from basic to class type with example.
17. Explain the conversion of data from class type to basic type with example.
18. Explain the conversion of data from one class to another class type with example.
19. Write a program to find the number of characters, number of words and number of lines
in a given text.
20. Write a program to set field width and display the given integer.
21. Write a program to enter the details of students like rollno, name, father’s name etc. of a
22. Write a program to input floating point numbers and set their precision to 5 decimal
40
places.
23. Write a program to convert the decimal number into its equivalent octal and
24. Write a program to convert the hexadecimal number into its equivalent decimal number
25. Write a program to convert a number into its equivalent scientific notation using
26. Write a program to enter some text upto 200 characters. Ignore vowels and replace them
void main ( )
cout.fill ( ^ );
cout.precision ( 3 );
cout.width ( 15 );
28. Write a program to create a single user-defined manipulator which provides following
a) 15 coulmn width
b) Left justified
41
c) Four digits precision
29. Write a program to convert minutes (integer type) to minutes and hours (object type) &
vice-versa.
30. Write a program to convert char* type variable to string type object.
31. Define a class vector. Find out the magnitude of vector as double type data by using
32. Write a program to declare two classes minutes and hours. Convert minutes to hours by
33. Write a program to convert integers or floats to complex type data by using both casting
34. Write a program to convert integers to date type data by using casting operator function.
42
https://www.youtube.com/watch?v=eWHzz-WHQh4
UNIT – IV
Different Forms of Inheritance – Single, Multiple, Multilevel, Hierarchical and Multipath Inheritance
Roles of Constructors and Destructors in Inheritance.
KURUKSHETRA UNIVERSITY,
KURUKSHETRA-136119
BCA III
Lesson no. 10
10.1 Introduction
10.2 Objectives
1
10.10 Error Handling Functions
10.12 Summary
2
10.1 Introduction
The main memory of the computer is limited and cannot hold large amount of data. The console I/O
functions read data through input devices and display on the screen. The data read through these
functions are temporarily stored in variables or arrays. The stored data vanishes when the program
ends. In order to store the data permanently, disk I/O functions are required which are associated
with disk files. Secondary storage devices such as Pen drives, DVDs, hard disks etc. are used to
store data in the form of files. A file is a collection of related data stored on the disk and created by
the user. Files are identified by their names. No two files can have the same name in the same
directory.
C++ provides file I/O functions to transfer data between program and disk files. It uses file streams
as an interface between the program and the files. The stream that supplies the data to the program
is known as input stream and the stream that receives the data from the program is known as output
stream. In this chapter, various file I/O functions for storing and retrieving the data from the files
will be discussed.
10.2 Objectives
Understand the concept of stream and classes for file streams in C++.
Describe input and output operations with files and error handling during the operations.
3
10.3 File Stream Classes
A File stream is an interface between the programs and the files provided by the I/O system. It is
nothing just a sequence of bytes. It acts either as a source from which input data can be obtained or
as a destination to which output data can be sent. The source stream that provides data to the
program is called input stream and the destination stream that receives data from the program is
known as output stream. In other words, the input stream reads data from the file and the output
The C++ contains a hierarchy of classes that are used to define the file handling functions. These
include ifstream, ofstream and fstream. The details and purpose of these classes are explained in
table 10.1. These classes are derived from fstreambase and are declared in fstream header file.
Therefore fstream.h must be included in any program that uses files. The hierarchy of file stream
classes used for input and output operations between files and program is shown in the figure 10.1.
filebuf Its purpose is to set the file buffers to read and write. Also contain open( ) and
close( ) as members.
fstreambase Serves as a base class for fstream, ifstream and ofstream class.
ifstream Provides input operations. Inherits get( ), getline( ),read( ), seekg( ) & tellg( )
functions from istream.
ofstream Provides output operations. Inherits put( ), write( ), seekp( ) & tellp( ) functions
from ostream.
fstream Provides support for simultaneous input and output operations.
4
ios
iostream file
iostream
------------------------------------------------------------------------------------------------------------------------
fstream file
filebuf
fstream base
For opening a file, firstly we have to create a file stream using the classes ifstream, ofstream and
fstream depending on the purpose that is whether we want to read data from the file or write data to
5
it and then link the file stream to the file name. A file name is a sequence of characters which may
contain two parts, a primary name and an optional period with extension. For example
Emp.doc
Student.xls
Here Emp & Student are primary names and doc & xls are extensions.
The first method is used for a single file in the stream but the second method is used for managing
i. Create a file stream object using the suitable class i.e. ofstream class is used for
ii. Initialize the file stream object with the file name.
The constructor uses the file name as argument and opens the file.
Here, fout is the object of ofstream class and the file student is opened for output i.e. data
can be written to it. Similarly, fin is the object of the ifstream class and the file test is
opened for input i.e. for reading the data from it.
The file stream objects like stream objects are used to write and read the data from the file
by using the overloaded operators << (insertion) and >> (extraction) respectively.
6
For example:
fin >> marks; // read contents of variable marks from test file
fin >> subject; // read contents of variable subject from test file
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
void main ( )
Here fout is the file stream object and the file named student is opened for writing. The
overloaded << insertion operator writes the data in the file. When a file is opened for writing
only, a new file is created if there is no file of that name and if a file exists already, then its
#include <iostream.h>
7
#include <fstream.h>
#include <conio.h>
void main ( )
# define N 30;
char line[N];
while(fin)
OUTPUT
Name Age
Ram 15
Jhon 16
Here, fin object is initialized with file name student. The file student is opened for reading
the data. The statement cout << line displays the data stored in the string line. When the end
In the above programs the files are automatically closed when the object expires i.e. when
the program terminates. Instead of using two programs, one for writing data and another for
8
reading data, a single program can be used for both operations by closing the file explicitly.
For this purpose member function close ( ) is used that closes the file associated with file
object.
For example
fout. close ( );
fin. close ( );
Here fout and fin are objects and files associated with the objects are closed respectively.
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
int main ( )
char name[30];
int Rollno;
9
ifstream fin ( “student”);
return 0;
OUTPUT
Roll No : 56
Here a single file student is used for both writing and reading the data. Firstly data is taken
from the keyboard and is written to the file. After the completion of writing, the file is
closed. Again the same file is opened, information that is already written to it, is read and
The function open ( ) is used to open multiple files sequentially by using the same stream
File-stream-class Stream-object;
10
Stream-object . Open (“filename”);
For example:
ofstream fout;
------------------
------------------
fout.close( );
-----------------
-----------------
fout.close( );
Here two files are opened in sequence for writing the data by the same file object.
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
int main ( )
11
fout.close ( ); // close fruit
while (fin)
while (fin)
12
fin.close ( ); // close vegetable
return 0;
OUTPUT
names of fruit :
apple
orange
banana
names of vegetable :
potato
tomato
cabbage
It is necessary to detect end of file because if the program does not detect end of file, it drops an
infinite loop. When end of file is detected, the process of reading the data can be terminated easily.
The function used for this purpose is eof ( ). The eof ( ) is a member function of ios class. It returns
In the previous program, the statement while (fin) is used. The object fin returns a value 0 if the end
of file is reached or any error occurs and the loop is terminated. Thus, the while loop terminates
when fin returns a value 0 on reaching the end of file condition. But remember here that this loop
13
may be terminated due to other failures as well. Therefore, the function eof ( ) is preferred.
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
int main ( )
while (fin.eof ( ) = = 0)
return 0;
OUTPUT
names of fruit :
apple
orange
banana
14
Here, the program reads and displays the contents of the file fruit. It reads the line till the eof ( )
returns a value 0. When it returns non-zero value, its means the file ends and the while loop is
terminated.
The function open ( ) is used to create new files as well as existing files. In the previous sections it
is used with one argument that was file name. However, this function can take two arguments, the
second one for specifying the file opening mode. The opening of file involves several modes
depending upon the operation to be carried out with the file. The syntax of the function open ( )
Where mode specifies the purpose for which the file is opened.
Table 10.2 explains various file mode parameters with their meanings.
Parameters Meaning
ios :: app Append data at the end of file.
ios :: ate After opening the pointer goes to the end of file.
ios :: binary Binary file
ios :: in Open file for reading only.
ios :: nocreate Open fails if the file does not exist.
ios :: noreplace Open the file if already exists.
ios :: out Open the file for writing only.
ios :: trunc Delete the contents of the file if it exists.
i.e. ios :: in for ifstream functions and ios :: out for ofstream functions.
There are some important points that should be remembered about the file opening modes.
i. The modes ios :: out and ios :: trunc are similar. Opening a file in ios :: out mode also opens
ii. The ios :: app is used only with the file capable of output.
iii. Both ios :: app and ios :: ate take the pointer at the end of file when it is opened. But the ios
:: app adds the data at the end of the file only where as ios :: ate allows us to add or modify
iv. It is not necessary to use mode parameters while creating a stream object of ifstream or
ofstream class.
v. The mode must be specified explicitly while using the object of fstream class because the
vi. The file can be opened by combining two or more mode parameters using the bitwise or
it opens the file in the append mode but fails to open if the file does not exist.
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
int main ( )
16
{
fout. open(“ fruit”, ios ::out); //open file fruit for writing only
fout. open(“ fruit”, ios ::app); //open fruit again in append mode
while (fin.eof ( ) = = 0)
17
{
while (fin.eof ( ) = = 0)
return 0;
OUTPUT
names of fruit :
apple
orange
banana
grapes
names of vegetable :
potato
18
tomato
cabbage
carrot
Here the files fruit and vegetable are opened first for writing only. The data is entered and the same
files are opened again in append mode for adding more data at the end of files. The same files are
Each file has two pointers associated with it, known as file pointers. One is known as input pointer (
or get pointer) and another is called output pointer (or put pointer ). The get pointer is used for
reading the contents at the specified location of a file and the put pointer is used to write the data to
The input pointer is automatically set at the beginning of the file when the file is opened in read
only mode. Similarly, when a file is opened in write only mode, the existing contents of the file are
deleted and the output pointer is set at the beginning of the file. Also the append mode moves the
output pointer to the end of the file. However, the functions explained in the table 10.3 are used to
move the file pointer to any desired location inside the file.
Function Purpose
seekg ( ) Moves get pointer to a specified location.
seekp ( ) Moves put pointer to a specified location.
tellg ( ) Gives the current position of the get pointer.
seekp ( ) Gives the current position of the put pointer.
19
For example, the statement
fin. seekg( 20 );
moves the file pointer fin to the byte number 20 or 21st byte in the file because the bytes are
int x = fout.tellp ( );
move the pointer at the end of the file fruit and the value of x gives the number of bytes in the file.
seekg( ) and seekp( ) can also be used with two arguments. The syntax is as under:
where offset represents the number of bytes the file pointer is to be moved from the location
20
The following program writes data in the file. Read the data from the end of the file and then
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
int main ( )
char name[30];
fin. seekg( 0, ios ::end ); // moves the pointer to end of the file.
char ch;
21
fin. seekg( -i, ios :: end); // moves backward by i bytes
fin >>ch;
return 0;
OUTPUT
enter name
darshan
nahsrad
There are various functions to perform read and write operations sequentially with the files. The get
( ) and put ( ) functions are used to read and write a single character whereas the functions read ( )
and write ( ) are designed to read and write blocks of binary data.
The get ( ) function is a member function of class fstream and reads a single character from
the file pointed by the get pointer. The put ( ) function is also a member function of fstream
class and writes a single character to the file associated with the stream object. Consider a
22
program in which a string is written in the file character by character and also read
sequentially.
#include <iostream.h>
#include <fstream.h>
#include <string.h>
int main ( )
char text[30];
F.seekg ( 0 );
char ch;
While (F.eof ( ) = = 0)
return 0;
23
OUTPUT
Enter data
Good Morning
Good Morning
The functions read ( ) and write ( ) handle the data in binary format. It means that data is
stored in the file in the same format in which it is stored in the internal memory. The main
advantage of binary format is that it is more accurate for storing the numbers as they are
stored in the exact internal representation and there is no need of conversions while saving
These functions take two arguments. The first is the address of variable var and the second
#include <iostream.h>
#include <fstream.h>
#include <string.h>
int main ( )
24
int number[ ] = { 10, 20, 30, 40, 50, 60 };
ofstream fout;
ifstream fin;
return 0;
OUTPUT
10 20 30 40 50 60
Here an integer array number [ ] is initialized with six integers. The data is stored using
write ( ) function in binary form and then read by using the read ( ) function. The same is
The functions read ( ) and write ( ) can also handle user-defined data types such as class
objects. The function write ( ) copies a class object from memory to file byte by byte with
25
no conversions. Similarly, the function read ( ) reads the class object from file to the internal
memory. It should be noted that only data members are read or write and the member
#include<iostream.h>
#include<fstream.h>
#include<iomanip.h>
class Vehicle
char Name[30];
float price;
public:
void getdata ( );
void display ( );
};
cin>>Name;
cin>>price;
26
{
void main ( )
fstream file;
Two_wheeler [i].getdata ( );
file.seekg(0);
Two_wheeler [i].display ( );
27
INPUT
OUTPUT
Name: Cycle
Price: 2500
Name: Scooter
Price: 35000
Price: 45000
Here details of vehicles are firstly written in the file and then read for displaying on the
screen. The read ( ) and write ( ) functions read and write entire data members of an object
as a single unit. The sizeof operator gives the sum total of lengths of all data members of the
object.
28
10.9 Random Access: Updating A File
These tasks require the file pointers to move to a particular location that corresponds to the
concerned data item and this can be implemented if the file contains a collection data of
items/objects of equal length. The location of the desired object (say nth) may be obtained as
follows:
here location gives the byte number of the first byte of the desired nth object.
Now file pointers seekg ( ), seekp ( ), tellg ( ), and tellp ( ) can be used to reach at the particular
location.
The following program uses the file “vehicles.dat” created in the previous program and adds a new
#include<iostream.h>
#include<fstream.h>
#include<iomanip.h>
class Vehicle
29
{
char Name[30];
float price;
public:
void getdata ( );
void display ( );
};
cin>>Name;
cin>>price;
void main ( )
Vehicle Two_wheeler;
fstream file;
30
file.open(“vehicles.dat”, ios :: ate | ios :: in | ios :: out | ios :: binary);
Two_wheeler.display ( );
Two_wheeler.getdata ( );
char ch;
cin.get(ch);
file.seekg(0);
Two_wheeler.display ( );
OUTPUT
31
Name: Cycle
Price: 2500
Name: Scooter
Price: 35000
Price: 45000
Name: Cycle
Price: 2500
Name: Scooter
Price: 35000
Price: 45000
Price: 38000
Here file is opened using ios :: ate for input and output operations which sets the file pointer at the
end of the file. Also clear ( ) function is used to reset the EOF flag and allows access to the file once
again.
32
10.10 Error Handling Functions
There are many situations which may create errors while performing operations with files.
The file name used for a new file may already exist.
The class ios contains various member functions that can be used to read the status recorded in the
file stream. These functions along with their meanings are described in the table 10.5
Function Meaning
bad( ) Returns true if a reading or writing operation fails. For example, in the case
that we try to write to a file that is not open for writing or if the device
where we try to write has no space left.
fail( ) Returns true in the same cases as bad( ), but also in the case that a format
error happens, like when an alphabetical character is extracted when we are
trying to read an integer number.
eof( ) Returns true if a file open for reading has reached the end.
good( ) It is the most generic state flag: returns true if no error has occurred.It
returns false in the same cases in which calling any of the previous
functions would return true. Note that good and bad are not exact opposites
(good checks more state flags at once).
33
The above functions may be used in the appropriate places in the program to find the status of the
ifstream fin;
………….
if ( fin . eof ( ) )
………….
………….
else
fin .clear( );
…………..
34
}
The function clear ( ) resets the error states (flags) so that further operations can be performed.
C++ also supports command line arguments that facilitates the supply of the arguments to the main
( ) function. An executable program that performs the specific task for the operating system is
called as command. The commands are issued from the command prompt. The arguments
associated with the commands are known as command line arguments. These are typed by the user
and delimited by a space. The first argument is always the filename (command name) and contains
Here, result is the name of the file containing the program to be executed and student and subject
are the file names passed to the program as command line arguments. The main ( ) function is now
written as
where argc denotes the number of arguments in the command line and second argument argv is an
array of char type pointers that points to the command line arguments. For the command line
Value of argc is 3 and argv would be an array of three pointers to strings as shown below:
35
Now argv[1] and argv[2] can be used as the file names in the file handling operations such as
10.12 Summary
A file is a collection of related data stored on the disk and created by the user.
Files are identified by their names. No two files can have the same name in the same
directory.
A File stream is an interface between the programs and the files provided by the I/O system.
The stream that supplies the data to the program is known as input stream and the stream
that receives the data from the program is known as output stream.
A file is opened in two ways: by using the constructor function of the class or by using the
The function close ( ) is used to close the file associated with file object.
The eof ( ) is a member function of ios class. It returns a non-zero value if end of file is
Different file opening modes are used to open the file depending upon the operation to be
The get pointer is used for reading the contents at the specified location of a file and the put
seekg( ) moves get pointer to a specified location and seekp ( ) moves put pointer to a
36
specified location.
tellg ( ) gives the current position of the get pointer and tellp ( ) gives the current position of
The get ( ) and put ( ) functions are used to read and write a single character whereas the
functions read ( ) and write ( ) are designed to read and write blocks of binary data.
The functions read ( ) and write ( ) can also handle user-defined data types such as class
objects.
The function clear ( ) resets the error states (flags) so that further operations can be
performed.
C++ also supports command line arguments that facilitates the supply of the arguments to
Object Oriented Programming With Ansi & Turbo C++ By Ashok N. Kamthane, Pearson
Education.
37
10.14 Self Assessment Questions
5. What are the different types of file opening modes? Explain with examples.
8. Explain the syntax of get ( ) and put ( ) functions with suitable examples.
9. Explain the syntax of read ( ) and write ( ) functions with suitable examples.
10. What are the possible reasons of errors during the file operations? Explain different error
12. What is the difference between sequential and random access file operations?
13. Write a program to read a file and display the contents of the file.
19. Write a program to detect end of file using the function eof ( ).
20. Write a program to open a file in binary mode and store float numbers in it.
38
21. Write a program to add and modify records in the text file.
22. Write a program to write contents of a file in reverse order in other file.
39