0% found this document useful (0 votes)
41 views357 pages

301 Oops C++

The document discusses object oriented programming features in C++ such as classes, objects, structures, scope resolution operator, static class members, local classes, and nested classes. It provides an introduction to object oriented programming concepts and how they are implemented in C++.

Uploaded by

Aditya Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views357 pages

301 Oops C++

The document discusses object oriented programming features in C++ such as classes, objects, structures, scope resolution operator, static class members, local classes, and nested classes. It provides an introduction to object oriented programming concepts and how they are implemented in C++.

Uploaded by

Aditya Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 357

UNIT – I

Object oriented Programming: Object-Oriented programming features and benefits. Object-Oriented


features of C++, Class and Objects, Structures, Scope resolution operator and its significance, Static Data
Members, Static member functions, Nested and Local Class.
Constructor, Initialization using constructor, types of constructor– Default, Parametrized & Copy
Constructors, Constructor overloading, Default Values to Parameters, Destructors.

https://www.youtube.com/watch?v=eWHzz-WHQh4

DIRECTORATE OF DISTANCE EDUCATION

KURUKSHETRA UNIVERSITY,

KURUKSHETRA-136119

BCA III

BCA - 301 (Object Oriented Programming Using C++)

Writer: Er. Matish Garg Vetter: Prof. Rajender Nath

Lesson No. 01

Object-Oriented Programming with C++

UNIT – I
Structure: https://www.youtube.com/
watch?v=eWHzz-WHQh4
1.1 Introduction

1.2 Objectives

1.3 Object Oriented Programming

1. 3.1 Features of Object Oriented Programming

1.3.2 Benefits of Object Oriented Programming

1.3.3 Applications of Object Oriented Programming

1.4 An introduction to C++

1.5 Classes and Objects

1.5.1 Declaring Objects

1.5.2 Accessing class members

1
1.5.3 Defining Member Functions

1.6 Structures in C++

1.7 Scope Resolution Operator and its Significance

1.8 Static Class members (Static data members & Static member functions)

1.9 Local Classes

1.10 Nested Classes

1.11 Summary

1.12 Suggested Readings

1.13 Self Assessment Questions

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

abstraction and encapsulation, Inheritance, polymorphism, message passing, reusability and

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

encapsulation. This lesson examines classes and objects in detail.

1.2 Objectives

After going through this lesson, you will be able to:

 Understand the Object Oriented Programming Features.

3
 Define classes and objects.

 Understand relation between structures and classes in C++.

 Understand the role of scope resolution operator in C++.

 Understand static member variables and functions.

1.3 Object Oriented Programming

Object Oriented Programming is an approach that provides a way of modularizing programs by

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

Oriented Programming is shown in table 1.1.

Object Oriented Programming Procedure Oriented Programming

Emphasis is on data as well as on procedures. Emphasis is on procedures.

Programs are divided into what are known as Large programs are divided into smaller

classes. programs known as functions.

Data is hidden and cannot be accessed by Data move openly around the system from

external functions. function to function.

New data and functions can be added Function transforms data from one form to

whenever necessary. another.

Follows Bottom-Up approach in program Follows Top-Up approach in program

design. design.

Table 1.1 Difference between OOP and procedure oriented programming

4
1.3.1 Features of Object Oriented Programming

It is necessary to understand some basic 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.

It is an instance of a class. It can be uniquely identified by its name and it defines

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
……….

Figure 1.1 Representation of an Object

5
ii) Class: A class is a collection of objects of the same kind. In other words, a class is a

lueprint, template, or prototype that defines and describes the static

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

class , then the statement

Bird Sparrow;

will create an object “Sparrow” belonging to the class “Bird”.

A class can be visualized as a three-compartment box, as illustrated in Figure 1.2.

a) Class name (or identifier): identifies the class.

b) Data members or variables (or attributes, states, fields): contains the static

attributes of the class.

c) Member functions (or methods, behaviors, operations): contains the dynamic

operations of the class.

Class Name
Data Members
(Static attributes)
Member Functions
(Dynamic operations)

Figure 1.2 A class as a 3-compartment box encapsulating data and functions

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

the objects and functions to operate on these attributes.

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

without modifying it.

7
Vehicle

Attributes

………….

Two Wheeler Four Wheeler

Attributes Attributes

…………. ………….

Bike Scooter Car Jeep

Attributes Attributes Attributes Attributes

…………. …………. …………. ………….

Figure 1.3 InInheritance

vi) Polymorphism: It means the ability to take more than one form. An operation may

exhibit different behaviours in different instances. The process of making an operator

to exhibit different behaviours in different instances is known as operator

overloading. Similarly we can use a single function name to perform different types

of tasks known as function overloading. The same function acts differently on

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

having different attributes act differently for different shapes.

8
SHAPE

Area ( )

CIRCLE RECTANGLE CYLINDER

Area (circle Attributes ) Area (Rectangle Attributes ) Area ( Cylinder Attributes)

Figure 1.4 Polymorphism

vii) Message Passing: In object-orientation, there is a view of autonomous objects which

communicate with each other by exchanging messages. Objects react when they

receive messages by applying methods on themselves. A message for an object is a

request for execution of a procedure and therefore will invoke a function in the

receiving object that generates the desired result. Message passing in figure 1.5

indicates the name of object, function and required data elements.

Object . Area ( argument ) ;

Object name

Communication Operator
Message
Data Elements

Figure 1.5 Message Passing

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

provides supports for generic programming. Template allows a single function or

class to work with different data types.

1.3.2 Benefits of Object Oriented Programming

Object-Oriented Programming has many benefits:

 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

concepts and abstractions. Ease in design leads to more productive software

development.

 Ease in software maintenance: object-oriented software are easier to understand,

therefore easier to test, debug, and maintain.

 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.

 Secure Programming: The information hiding feature facilitates the developer to

design and develop safe programs that do not disturb the code in other parts of the

program.

 Integrity: Redundant program codes can be eliminated by using inheritance.

10
1.3.3 Applications of Object Oriented Programming

The major application areas of OOP are as under:

 Real Time Systems

 Simulation and modeling

 Object Oriented Databases

 Neural networks and parallel programming

 Office Automation , CAD/CAM Systems

1.4 An introduction to C++

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-

purpose programming language designed by Bjarne Stroustrup as an extension to the C

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

making C++ a truly object- oriented language.

Salient Features of C++:

 C++ is C: C++ supports (almost) all the features of C. Like C, C++ allows programmers to

manage the memory directly, so as to develop efficient programs.

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

apply the same algorithm to different data types.

 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

Template Library (STL).

1.5 Classes and Objects

A class provides an approach to pack the data and its related functions together. It can be

visualized as a three- compartment box, as illustrated:

i) Class name (or identifier): identifies the class.

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

the same class. The syntax of class declaration is as under:

class < Name of Class>

private:

Declaration of Variables;

Prototype declaration of Functions;

public:

Declaration of Variables;

Prototype declaration of Functions;

} object-list; //the object –list is optional. If present, it declares

//objects of the class.

The following example illustrates the class Circle declaration.

class Circle // class name

private:

double radius; // data members ( or variables)

public:

double getRadius(); // member functions

13
double showArea();

};

1.5.1 Declaring Objects

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

the function main ( ) as follows:

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.

1.5.2 Accessing class members

The object can access the public member variables and functions of a class by using dot operator

(.) and arrow operator ( - > ). The syntax is as follows:

[Object name] [Operator][Member name];

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

Access Specifier Class Members Class Objects

public allowed allowed

private allowed Not allowed

protected allowed Not allowed

Table 1.2 Access Specifiers

1.5.3 Defining Member Functions

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.

(i) Member Function 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:

double getRadius( ) // Member function (Getter)

radius=1.5;

double showArea() // Member function

return radius*radius*3.1416;

};

int main( )

clrscr( );

Circle C1;

C1. getRadius( );

cout<< “ area” << C1. showArea( );

return 0;

16
(ii) Member function outside the class

To define a function outside the class the following steps must be taken:

 The prototype of function must be declared inside the class.

 The function name must be preceded by the class name and its return type separated

by scope access operator.

The following example illustrates the function outside the class.

#include <iostream.h>

class Circle

private:

double radius;

public:

void getRadius( ) ; // Prototype declaration

double showArea( ) ; // Prototype declaration

};

void circle :: getRadius()

radius=1.5;

double circle :: showArea ()

return radius*radius*3.1416;

17
int main( )

clrscr( );

Circle c1;

c1. getRadius( );

cout<< “ area” << c1. showArea( );

return 0;

1.6 Structures in C++

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:

struct < Structure Name>

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

three member variables Bname, Qty and Price.

The structure name Book can be used to create any number of variables of type Book by using

the following declaration in C.

struct Book B;

where B is a variable or instance of type Book.

Limitations of Structures in C:

In C language, the structures have following limitations:

 Functions cannot be declared as members in the structures in C language.

 They do not allow data hiding as direct access to data members is possible.

 The data members cannot be initialized inside the structure.

 It is compulsory to use struct keyword for declaring objects.

Improvements in Structures in C++

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.

 The use of struct keyword for declaring objects is eliminated.

19
 Structures allow data hiding in C++ as some of their members can be declared as private.

Let us take an example

# include < iostream.h>

# include < constream.h>

struct Book

void getbook( ); // public

void showbook ( ); // public

private:

char Bname[30];

int Qty;

float Price;

};

void Book : getbook( )

Bname = “C++”;

Qty = 2;

Price = 228.5;

void Book : showbook( )

Printf( “\n Book name = %s”, Bname);

20
Printf( “\n Quantity = %d”, Qty);

Printf( “\n Price = %f”, Price);

void main ( )

Book b1, *b2; // object declaration

b1. getbook ( ); // with simple object

b1. showbook ( );

b2 -> getbook ( ); // with pointer to structure

b2 -> showbook ( );

OUTPUT

Book name = C++

Quantity = 2

Price =228.5

Book name = C++

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

before the structure name.

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,

structures and classes are equivalent.

1.7 Scope Resolution Operator and its Significance

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

Let us take an example

# include <iostream.h>

# include <constream.h>

int a =1; // globally declared

void main ( )

int a = 2; // redeclared , local to main ( )

………..

int b = a ; // assign the value to another variable

int a = 3; // redeclared again

cout<< “ in inner block \n”

cout<< “ b = ” << b << “\n”;

cout<< “ a = ” << a << “\n”;

cout<< “ : : a = ” << : : a << “\n”;

………..

………..

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

inner block, : : a refers to the value 1 and not 2.

The main significance of the scope resolution operator is in the classes to identify the class to

which a member function belongs.

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

define static members. The Syntax is

static < variable definition>

static < function definition>

Examples are

static int c;

static void display ( )

25
…………….

A static member is referenced via scope resolution operator in the form of

ClassName :: VariableName or ClassName :: FunctionName( ).

 It can be used to implement "global" class variables and functions that can be used

without creating instances of a class.

 It can also be used to share information among all instances, e.g., a count on the

number of instances created.

 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

instance is created). It can be invoked using the class name.

The following example displays the value of static data member.

#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++;

static void display( )

cout<< “ \n value of c :” << 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.

There are some limitations in constructing local classes.

 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

inside the function.

 All the member functions must be declared within the class declaration.

 The static variables cannot be declared inside a local class.

 The enclosing function cannot access the private members of a local class.

The following program illustrates the concept of local classes.

#include <iostream.h>

#include <conio.h>

void Result ( );

void main ( )

clrscr ( );

Result ( );

29
void Result ( )

class Sum

int a, b;

public:

void get( int x, int y)

a = x;

b = y;

int show ( )

return a+b;

};

Sum S;

S. get (45, 56);

cout<< “ Result is ”<< S. show ( );

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 ( )

returns the sum of these two integers.

1.10 Nested Classes

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

seldom used. The following example illustrates the nested classes.

#include <iostream.h>

#include <conio.h>

class Student

char Name[20];

public:

void getname( )

cout<< “ enter name of student\n”;

cin>> Name;

31
void showname( )

cout<< “\n”<< Name << “ : ”;

class Test // Nested Class

int marks;

public:

void getmarks (int a )

Marks = a;

void showmarks( )

cout<< marks;

}; // end of nested class

}; // end of host class

void main ( )

clrscr( );

Student S; // object of host class

Student : : Test T; // object of nested class

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

class. You can declare any number of classes inside a class.

1.11 Summary

 OOP allows decomposition of a problem into a number of entities called objects and then

builds data and functions in object-oriented programs.

 Object is an instance of a class.

 A class is a collection of objects of the same kind.

 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

objects of another class.

 Polymorphism means one name multiple forms.

 Objects communicate with each other by exchanging messages.

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.

 C++ includes advance feature of exception handling which provides an integrated

approach to detect and report runtime problems in order to take proper action.

 Object oriented technology offers several benefits like Reusability.

 Real time business system is the major application area of OOP.

 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.

 Defining objects of class data type is known as class instantiation.

 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 class member.

 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

related data items of different types.

 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

the scope of the variable.

 Scope Resolution Operator ( : : ) is used to access the global version of the variable from

within the inner block.

 The main application of the scope resolution operator is in the classes to identify the class

to which a member function belongs.

 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.

 A class which is defined with in another class is known as nested class.

1.12 Suggested Readings

 Object Oriented Programming With C++ By E Balagurusamy, TMH.

 Object Oriented Programming With Ansi & Turbo C++ By Ashok N. Kamthane, Pearson

Education.

 The Complete Reference C++ By Herbert Schildt, TMH

 The C++ Programming Language By Bjarne Stroustrup, Pearson Education.

 Object Oriented Programming in C++ By Roberrt Lafore, SAMS Publishing.

35
1.13 Self Assessment Questions

1. What is Object Oriented Programming? How is it different from Procedure Oriented

Programming?

2. What are the advantages of Object Oriented Programming?

3. Differentiate between

a. Object and Class

b. Inheritance and Polymorphism

c. Data abstraction and Data encapsulation

4. List a few areas of application of OO technology.

5. What is a class? How does a C++ class differ from a C++ structure? Explain by an

example.

6. What are objects? How are they created in C++?

7. Define Scope Resolution Operator. What is significance of Scope Resolution Operator?

Explain with 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.

10. What are the Limitations of Local classes?

11. What are nested 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

BCA - 301 (Object Oriented Programming Using C++)

Writer: Er. Matish Garg Vetter: Prof. Rajender Nath

Lesson No. 02

Constructors and Destructors


UNIT – I
Structure:

2.1 Introduction

2.2 Objectives

2.3 Constructors and Destructors

2.4 Constructors

2.4.1 Characteristics of Constructors

2.5 Types of Constructors

2.5.1 Default Constructor

2.5.2 Parameterized Constructor

2.5.3 Copy Constructor

2.6 Constructor Overloading

1
2.7 Default Values to Parameters in Constructors

2.8 Destructors

2.8.1 Characteristics of Destructors

2.9 Summary

2.10 Suggested Readings

2.11 Self Assessment Questions

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

After going through this lesson, you will be able to:

 Define constructors and destructors.

 Explain the characteristics of constructors and destructors.

 Understand different types of constructors and their use in programming.

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

difference is that destructor is preceded by ~ (tilde) operator.

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:

Number (void); // Declaration of Constructor

……………..

4
};

Number : : Number ( void ) // Definition of Constructor

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
{

cout<< “\n”<<P<< “\n” <<Q<< “\n”<<R;

};

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

initialized to constant values as given in the constructor definition.

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

example illustrates this.

6
#include <iostream.h>

#include <conio.h>

class Number

int P,Q,R;

public:

Number ( )

cout<< “ \n Constructor invoked.”;

P = 10;

Q = 20;

R = 30;

cout<< “P = ”<<P<< “, Q = ” <<Q<< “, R = ”<<R;

};

void main ( )

clrscr ( );

Number X, Y, Z;

OUTPUT

Constructor invoked. P = 10, Q = 20, R = 30

7
Constructor invoked. P = 10, Q = 20, R = 30

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

constructor is invoked three times i.e. equal to the number of objects.

2.4.1 Characteristics of Constructors

Some special characteristics of constructors are summarized as follows:

I. Constructor has the same name as that of the class it belongs to.

II. The constructor is invoked automatically when the object is declared.

III. Constructors have neither return type nor void.

IV. They should be declared in the public section of the class.

V. Constructors cannot be virtual.

VI. They cannot be inherited. However a derived class constructor can call the base class

constructor.

VII. They can have default arguments like other functions.

VIII. The constructors can also be defined as inline functions.

IX. The constructors can be overloaded.

X. The constructor without arguments is called as default constructor.

XI. A reference of an object can be passed to the constructor called copy constructor.

2.5 Types of Constructors

Constructors are of three types as shown in figure 2.1.

8
 default constructor

 parameterized constructor

 copy constructor

Constructors

Default Parameterized Copy

Figure 2.1 Types of Constructors

The constructor without arguments is called as default constructor. The constructors with

arguments are called parameterized constructors. When a reference of object is passed as

argument to the constructor then it is called copy constructor.

2.5.1 Default Constructor

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:

IntergerSum(void); // Declaration of Default Constructor

int display( void);

};

Integersum : : IntergerSum( ) // Definition of Default Constructor

a = 5;

b = 10;

int IntergerSum : : display ( )

return a + b;

void main ( )

clrscr( );

IntegerSum Sum1;

cout<< “ Sum = ”<< Sum1.display( );

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.

2.5.2 Parameterized Constructor

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:

i. By calling the constructor implicitly.

ii. By calling the constructor explicitly.

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:

IntergerSum( int x, int y=0) // Parameterized Constructor

11
a= x;

b = y;

int display ( )

return a + b;

void main ( )

clrscr( );

IntegerSum Sum1( 6 ); // Constructor called Implicitly

IntegerSum Sum2 = InterSum( 35, 25 ); // Constructor called Explicitly

cout<< “ Sum = ”<< Sum1.display( );

cout<< “ Sum = ”<< Sum2.display( );

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.

2.5.3 Copy Constructor

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:

IntergerSum( int x, int y) // Parameterized Constructor

a= x;

b = y;

IntergerSum( IntegerSum &I) // Copy Constructor

{
13
a = I.a;

b = I.b;

int display ( )

return a + b;

void main ( )

clrscr( );

IntegerSum Sum1 (10, 20);

IntegerSum Sum2 (Sum1);

IntegerSum Sum3 = Sum1;

cout<< “ Sum = ”<< Sum1.display( );

cout<< “ Sum = ”<< Sum2.display( );

cout<< “ Sum = ”<< Sum3.display( );

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

IntegerSum Sum2 (Sum1);

IntegerSum Sum3 = Sum1;

have same meanings.

2.6 Constructor Overloading

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:

Circle ( ) // Default Constructor

15
radius=0;

Circle (double r) // Parameterized Constructor

radius = r;

Circle (Circle &c2) // Copy Constructor

radius = c2.radius;

double showArea( ) // Member function

return radius*radius*3.1416;

};

int main( )

clrscr ( );

Circle c1, c2 (3.5);

Circle c3 (c2);

Circle c4=c2;

cout<< “ area =” << c2. showArea ( );

16
cout<< “ area =” << c3. showArea ( );

cout<< “ area =” << c4. 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.

Let us take another example of class Addition with overloaded constructors.

#include <iostream.h>

#include <conio.h>

class Addition

private:

int a, b, c;

public:

17
Addition ( ) // Default Constructor

{ // No argument

a = 0;

b = 0;

Addition ( int x ) // Parameterized Constructor1

{ // Single argument

a = x;

b = x;

Addition ( int x, int y ) // Parameterized Constructor2

{ // Two arguments

a = x;

b = y;

int show( ) // Member function

c = a + b;

return c;

};

int main( )

18
{

clrscr ( );

Addition A1;

Addition A2 (45);

Addition A3 (45, 55);

cout<< “ Sum of two numbers is =” << A1. show ( );

cout<< “ Sum of two numbers is =” << A2. show ( );

cout<< “ Sum of two numbers is =” << A3. show ( );

return 0;

OUTPUT

Sum of two numbers is = 0

Sum of two numbers is = 90

Sum of two numbers is = 100

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.

2.7 Default Values to Parameters in Constructors

A constructor can be defined with default arguments. Consider the declaration of following

constructor:

19
Addition ( int a, int b = 20);

The default value of argument b is 20. Therefore the statement

Addition A1 ( 30 );

assigns the value 30 to a and 20 to b ( by default ). However the statement

Addition A1 (30, 40);

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:

long principal , rate, year;

float Amount;

public:

Interest (int p, int t, int r = 5) // Default Argument

Principal = p;

year = t;

rate = r;

20
void display_amont ( )

cout<< “\n Principal =” << Principal;

cout<< “ \nRate of Interest =” << rate;

cout<< “ \n year =” << year;

Amount = (Principal * rate * rate)/ 100;

cout<< “\n Amount = ”<<Amount;

};

int main( )

clrscr ( );

Interest I1 (5000, 3);

Interest I2 (5500, 5, 10);

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:

Circle ( ) // Constructor with no argument

radius=0;

Circle (double r) // Constructor with one argument

radius = r;

~ Circle ( ) // Destructor

cout<< “\n object destroyed”;

double showArea( ) // Member function

return radius*radius*3.1416;

};

int main( )

clrscr( );

23
Circle c1, c2 (3.5);

cout<< “ area = ” << c2. showArea ( );

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.

2.8.1 Characteristics of Destructors

Some important characteristics are summarized as follows:

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.

III. Destructors can be virtual.

IV. The destructors do not have any arguments.

V. The destructors cannot have default values.

VI. They cannot be overloaded.

VII. They cannot be inherited. However a derived class can call the base class destructor.

24
2.9 Summary

 A Constructor is a special function which is used to initialize an object at its definition

time. It has same name as that of class it belongs to.

 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 have neither return type nor void.

 The constructors can be overloaded.

 Constructors are of three types: default constructor, parameterized constructor and copy

constructor

 The constructor without arguments is called as default constructor.

 The constructors with arguments are called parameterized constructors.

 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.

 The destructors do not have any arguments.

 The destructors cannot have default values.

 They cannot be overloaded.

 If there is no destructor in a class, a default destructor is generated by the compiler.

25
2.10 Suggested Readings

 Object Oriented Programming With C++ By E Balagurusamy, TMH.

 Object Oriented Programming With Ansi & Turbo C++ By Ashok N. Kamthane, Pearson

Education.

 The Complete Reference C++ By Herbert Schildt, TMH

 The C++ Programming Language By Bjarne Stroustrup, Pearson Education.

 Object Oriented Programming in C++ By Roberrt Lafore, SAMS Publishing.

2.11 Self Assessment Questions

1. What is a Constructor? Is it necessary to use constructors in a class?

2. What is Destructor? How is it important in a class?

3. Differentiate between constructors and destructors with examples.

4. Explain the characteristics of constructors.

5. Explain the characteristics of destructors.

6. What is default constructor? Give an example.

7. Define parameterized constructor with examples.

8. What is copy constructor? Give an example.

9. Whether constructors are overloaded or not? Explain with examples.

10. What is the difference between default constructor and default argument constructor?

Explain with an example.

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.

13. Write a program to find the transpose of a matrix.

14. Write a program to generate Fibonacci series using constructors.

27
UNIT – II
Manipulators, Friend Function, Friend Class, Arrays, Array of Objects, Passing and Returning Objects to
Functions, String Handling in C++,

Dynamic Memory Management: Pointers, new and delete Operator,


Array of Pointers to Objects, this Pointer, Passing Parameters to Functions by Reference & pointers.

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

BCA - 301 (Object Oriented Programming Using C++)

Writer: Er. Matish Garg Vetter: Prof. Rajender Nath

Lesson No. 03

Functions and Pointers


UNIT – II
Structure:

3.1 Introduction

3.2 Objectives

3.3 Functions

3.3.1 Calling a function

3.3.2 The return statement

3.4 Actual and Formal Parameters

3.5 Parameter passing in Functions

3.5.1 Passing Objects to Functions

3.5.2 Returning Objects

3.6 Inline Functions

1
3.7 Friend Functions

3.8 Friend Class

3.9 Pointers

3.9.1 Operation on Pointers

3.10 this pointer

3.11 Dynamic memory management

3.12 Summary

3.13 Suggested Readings

3.14 Self Assessment Questions

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

themselves for performing some specific tasks.

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

After going through this lesson, you will be able to:

 Describe the concept of functions and their use in programming.

 Describe different features and applications of functions.

 Understand inline functions and their use in C++.

3
 Understand the concept of Friend Function and Friend Class.

 Describe the manipulators to format the output.

 Understand the concept of Pointers and their applications in C++.

 Understand memory allocation and deallocation at run-time.

3.3 Functions

A function is defined as a self-contained block of code/instructions that performs a specific

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_type Fname (parameter_list); // Function prototype

return_type Fname (parameter_list) //Function Definition

……………..…. // Function Body

return (expression);

The first statement is Function prototype which gives the following details of the function to

the compiler:

I. Name of function

II. Type of value returned

III. Type & number of arguments used.

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

must be terminated by semicolon. The example of function prototype is

float Sum( int a, int b, float c);

A function prototype can skip the argument names but a function definition cannot. For example

float Sum( int, int, float);

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 Sum( int x, int y, float z)

float s = x + y + z;

return s;

This function computes the sum of three numbers and returns the result as float value.

3.3.1 Calling a Function

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>

float volume(float, float, float); // Function prototype

void main ( )

float l, b, h, vol;

clrscr ( );

cout<< “Enter the length, breadth and height of object\n”;

cin>> l>>b>>h;

vol = volume (l, b, h); // Function calling

cout<< “ Volume of object is ”<< vol << “ \n”;

getch( );

float volume ( float x, float y, float z) //Called Function definition

float v;

v = x * y * z;

return (v); // the return statement

6
OUTPUT

Enter the length, breadth and height of object

2.5 5 10

Volume of object is 125

Here, in the above program the function volume is called in the main ( ) by using the statement

vol = volume (l, b, h);

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

the returned value is assigned to the variable vol.

3.3.2 The return statement

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 termination of the function.

The return statement can return only one value. It can be used anywhere in the function and also

a function can contain any number of return statements. For example:

int Greater ( int a , int b)

7
{

if ( a > b )

return a;

else

return b;

The function Greater ( ) returns a if a is greater than b otherwise it returns b.

When the user wants to return more than one values from function, the values should be passed

by address or by reference method which are discussed in the next section.

3.4 Actual and Formal Parameters

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>

float multiply (float, float); // Function prototype

void main ( )

8
float x, y, z;

clrscr ( );

cout<< “Enter the numbers\n”;

cin>> x>>y;

z = multiply (x, y); // Actual Arguments

cout<< “ Multiplication of two numbers is ”<< z << “ \n”;

getch( );

float multiply ( float a, float b) // Formal Arguments

float c;

c = a * b;

return (c); // the return statement

OUTPUT

Enter the numbers

5 10

Multiplication of two numbers is 50

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

between a function call and the function itself.

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

arguments are appeared as garbage.

3.5 Parameter passing in Functions

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

parameters can be passed to the functions.

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

function the changes made vanish. Consider the following example :

#include <iostream.h>

#include <conio.h>

void change_value ( int, int );

void main ( )

10
{

int x, y;

clrscr ( );

cout<< “Enter the numbers\n”;

cin>> x>>y;

cout<< “ Before calling in main\n ”;

cout<< “ x = ”<<x << “ y = ”<<y<<“ \n”;

change_value (x,y);

cout<< “ After calling in main\n ”;

cout<< “ x = ”<<x << “ y = ”<<y<<“ \n”;

getch( );

void change_value ( int a, int b)

int temp;

temp = a;

a = b;

b = temp;

cout<< “ In Function change_value\n ”;

cout<< “ x = ”<<a << “ y = ”<<b<<“ \n”;

OUTPUT

Enter the numbers

11
5 10

Before calling in main

x = 5 y = 10

In Function change_value

x = 10 y = 5

After calling in main

x = 5 y = 10

In the above program, values of actual arguments x and y are passed to the function

change_value ( ). The formal arguments a and b in function change_value ( ) get these

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

copies of actual arguments and both have different addresses.

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 change_value ( int*, int* );

void main ( )

12
int x, y;

clrscr ( );

cout<< “Enter the numbers\n”;

cin>> x>>y;

cout<< “ Before calling in main\n ”;

cout<< “ x = ”<<x << “ y = ”<<y<<“ \n”;

change_value (&x , &y);

cout<< “ After calling in main\n ”;

cout<< “ x = ”<<x << “ y = ”<<y<<“ \n”;

getch( );

void change_value ( int *a, int *b)

int *temp;

*temp = *a;

*a = *b;

*b = *temp;

cout<< “ In Function change_value\n ”;

cout<< “ x = ”<<a << “ y = ”<<b<<“ \n”;

OUTPUT

Enter the numbers

5 10

13
Before calling in main

x = 5 y = 10

In Function change_value

x = 10 y = 5

After calling in main

x = 10 y = 5

In the above program, instead of values, addresses of actual arguments x and y are passed

to the function change_value ( ). The formal arguments a and b in function change_value

( ) 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 change_value ( int&, int& );

void main ( )

int x, y;

clrscr ( );

cout<< “Enter the numbers\n”;

cin>> x>>y;

cout<< “ Before calling in main\n ”;

cout<< “ x = ”<<x << “ y = ”<<y<<“ \n”;

change_value (x,y);

cout<< “ After calling in main\n ”;

cout<< “ x = ”<<x << “ y = ”<<y<<“ \n”;

getch( );

void change_value ( int &a, int &b)

int temp;

temp = a;

a = b;

b = temp;

cout<< “ In Function change_value\n ”;

cout<< “ x = ”<<a << “ y = ”<<b<<“ \n”;

15
}

OUTPUT

Enter the numbers

5 10

Before calling in main

x = 5 y = 10

In Function change_value

x = 10 y = 5

After calling in main

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

addresses and therefore changes are permanent.

3.5.1 Passing Objects to Functions

Similar to variables, an object may be passed to functions by using all the three methods as

discussed above in previous section i.e.

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

copies of object are stored at different locations.

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

passed to function explicitly by using pointers.

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

methods is similar to that of normal variables as discussed above. Consider an example of

adding two matrices using call by value method.

#include <iostream.h>

#include <conio.h>

class matrix

int m[2][2];

public:

void getdata( )

int i, j;

cout<< “ Enter the elements of 2x2 matrix \n”;

for( i=0; i<2; i++)

for( j=0; j<2; j++)

cout<< “m[”<<i<<“] [”<< j<< “] = ”;

17
cin>> m[i][j];

void display ( )

int i, j;

for( i=0; i<2; i++)

cout<< “\n”;

for( j=0; j<2; j++)

cout<< m[i][j] << “\t”;

void addition ( matrix, matrix);

};

void matrix : : addition ( matrix m1 , matrix m2)

int i, j;

for( i=0; i<2; i++)

for( j=0; j<2; j++)

m[i][j] = m1. m[i][j] + m2. m[i][j];

18
}

int main ( )

matrix M1, M2, M3;

M1. getdata ( );

M2. getdata ( );

M3. addition ( M1, M2 ); // passing objects as arguments

cout<< “ \nResultant matrix after addition :”;

M3. display ( );

return (0);

OUTPUT

Enter the elements of 2x2 matrix

m[0] [0] = 4

m[0] [1] = 2

m[1] [0] = 3

m[1] [1] = 1

Enter the elements of 2x2 matrix

m[0] [0] = 5

m[0] [1] = 7

19
m[1] [0] = 1

m[1] [1] = 1

Resultant matrix after addition:

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

pass an object by reference, the prototype of function addition ( ) should be as follows:

void addition ( matrix&, matrix&);

In case of passing an object by address, the prototype of function addition ( ) should be as

follows:

void addition ( matrix*, matrix*);

and the function should be called by using the statement

M3. addition ( &M1, &M2);

Also the member variables of objects M1 and M2 can be accessed only by the operator ( -> ) like

M1 -> m[i][j] and M2 -> m[i][j].

3.5.2 Returning Objects

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:

void getdata( float real, float img )

a = real;

b = img;

void display ( Complex c )

cout << c. a << “ + i ” << c. b << “\n”;

friend Complex Sum ( Complex, Complex);

};

Complex Sum (Complex c1 , Complex c2)

Complex c3;

c3. a = c1. a + c2. a;

c3. b = c1. b + c2. b;

return ( c3); // returning object c3

21
}

int main ( )

Complex X, Y, Z;

X. getdata ( 5.2, 4.0);

Y. getdata ( 3.0, 5.6);

Z = Sum( X, Y); // passing objects as arguments

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

declarator as shown below:

inline < return type > < class name> :: function name ( signature)

The example is as under:

#include <iostream.h>

class Circle

private:

double radius;

public:

void getRadius( ) ; // Prototype declaration

double showArea( ) ; // Prototype declaration

};

inline void circle :: getRadius()

radius=1.5;

23
inline double circle :: showArea()

return radius*radius*3.1416;

int main( )

clrscr( );

Circle c1;

c1. getRadius( );

cout<< “ area” << c1. showArea( );

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

be taken while using inline functions:

I. Functions should not be recursive.

II. Functions should not contain static variables.

24
III. Functions should not contain control structures like for loop, while loop, a switch or goto

statement.

IV. The function main ( ) cannot work as inline.

3.7 Friend Functions

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.

The syntax of declaration of function is as under:

class < class name>

…………

public:

…………

friend < return type> <function name>(<argument type>);

};

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.

The friend functions have certain properties:

I. The friend function is not in the scope of the class to which it is declared; therefore it is

called without using object name.

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

the object of a class and member is member function or data member.

III. Generally friend functions have the objects as arguments.

IV. It can be declared anywhere in the class without affecting its meaning and scope.

V. Friend function of a class can be a member function of another class.

Let us take an example of ‘Account’ class to access its private data like Acc_No. , Name,

Amount to calculate the TDS by using a non-member function TDS_Cal.

#include <iostream.h>

# include < conio.h>

class Account

private:

char name[18];

int acc_no;

float amount;

public:

void getData( )

cout << “ \n Name :” ;

cin >> name;

26
cout << “ \n acc_no :”;

cin >> acc_no;

cout << “ \n Amount :” ;

cin >> amount;

friend void TDS_Cal(Account);

};

void TDS_Cal (Account ac)

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

Tds of account no. 234223 is Rs. 5600

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

TDS_Cal calculates and displays the TDS.

3.8 Friend Classes

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

shown by the function of a class by making it friend to another class.

#include <iostream.h>

#include <conio.h>

class Y;

class X

28
int x ;

public:

void read_value1( )

x=25;

void display (Y);

};

class Y

int y;

public :

void read_value2( )

y = 45;

friend void X :: display ( Y );

};

void X :: display (Y y)

cout << “ \n x =” << x;

cout << “ \n y =” << 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

the values of data members of both classes.

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

that Ptr is pointer variable which contains the address of variable a.

30
Pointer variable Normal variable

Ptr a
4090 10

4090

address of variable

Figure 3.1 Pointer Variable holding address of another 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

of declaration of a pointer variable is as under:

data-type *pointer variable;

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

program, x and p provide the addresses of y and q respectively.

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;

cout<< “\n y =”<< y << “\t &y =” <<(unsigned)&y;

cout<< “\n *x =”<< *x << “\t x =” <<(unsigned)x;

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

space dynamically that leads to save the memory space.

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.

v. Pointers simplify the representation of multi-dimensional arrays.

vi. Pointers are used to create data structures like stacks, queues, lists etc.

vii. A pointer can be incremented or decremented.

viii. An integer can be added or subtracted from the pointer.

ix. One pointer can be subtracted from another but addition of two pointers would never

work out.

x. Division and multiplication operations also would not work.

3.9.1 Operation on Pointers

The following operations can be performed with pointers:

 Assignment Operation: Pointers of same type can be assigned to each other.

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

the same location or variable Y. The following program illustrates it.

#include <iostream.h>

#include <conio.h>

33
void main ( )

int *P, *Q, X , Y;

clrscr ( );

X = 15;

Y = 25;

P = &X;

Q = &Y;

cout<< “\n Before Assignment”;

cout<< “\n The value of P is ” <<(unsigned)P;

cout<< “\n The value of Qis ” <<(unsigned)Q;

P = Q;

cout<< “\n After Assignment”;

cout<< “\n The value of P is ” <<(unsigned)P;

cout<< “\n The value of Q is ” <<(unsigned)Q;

getch( );

OUTPUT

Before Assignment

The value of P is 6064

The value of Q is 6062

After Assignment

34
The value of P is 6062

The value of Q 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;

Where P and Q are the pointers of same data type.

 Increment and decrement: A Pointer can be incremented or decremented by using

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.

For example P ++ ; // increment

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

incremented by 1, for a float variable it is incremented by 4 and so on. For example if x is

a integer pointer with an initial value say 1256 then x++ increments its value by 2 i.e.

after this statement the value of x will be 1258.

 Adding an integer or subtracting an integer from pointer: C++ allows adding or

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.

3.10 this pointer

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 statement a = 25 can be written as this - > a = 25.

The pointer this is also used to return the object it points to. The statement is

return *this;

Consider the following example:

#include <iostream.h>

#include <conio.h>

class Student

36
{

Char name [20];

float marks ;

public:

Student ( char *s, float m )

strcpy ( name, s);

marks = m;

Student & Student : : greater ( Student & x)

if ( x. marks >= marks)

return x;

else

return *this;

void Display( )

cout<< “ Name: ”<<name<< “\n”;

cout << “ Marks: ”<< marks;

};

void main ( )

37
{

Student S1 (“ Ram ” , 67), S2 (“ Mohit ”, 72.5);

Student S = S1.greater (S2);

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.

3.11 Dynamic memory management

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.

The general forms of new and delete are:

pointer_var = new type;

Delete pointer_var;

For example:

#include <iostream.h>

38
#include<conio.h>

int main( )

clrscr( );

int *p;

p=new int; // dynamically allocate an int and assign its

//address to pointer

*p=123;

cout<< “ At address ” << p<< “the value is”<< *p;

delete p;

return 0;

The memory can be allocated dynamically to arrays using ‘new’ and deallocated using ‘delete’

operators.

The general form is

Pointer_var= new array_type[size];

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

is freed, its destructor is executed. The general form is

Ptr = new < classname>;

39
delete ptr;

Let us take our example of Circle.

#include <iostream.h>

#include <conio.h>

class Circle

private:

double radius;

double area;

public:

Circle ( ) // Constructor

{ cout<< “\n constructor”;

area = 0;

radius = 5.6;

~ Circle ( ) // Destructor

cout<< “\n destructor”;

void showArea( ) // Member function

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

 A function is defined as a self-contained block of code/instructions that performs a

specific coherent task.

 A function is used in the program only when a call to function is invoked.

41
 The return statement is used to return value to the calling function.

 The return statement can return only one value.

 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.

 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

value, call by address and call by reference.

 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

to the actual arguments in the calling function.

 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

place of function call in the caller function.

 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

called without using object name.

42
 Generally friend functions have the objects as arguments.

 Friend function of a class can be a member function of another class.

 When all the functions of a class need to access another class then that entire class can be

declared as friend class.

 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

the ios functions and flags.

 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

same data type.

 The pointer assigns the memory space dynamically that leads to save the memory space.

 A pointer can be incremented or decremented.

 An integer can be added or subtracted from the pointer.

 One pointer can be subtracted from another but addition of two pointers would never

work out.

 this pointer is used to represent an object that invokes a member function.

 this pointer is also used to return the object it points to.

 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.

3.13 Suggested Readings

 Object Oriented Programming With C++ By E Balagurusamy, TMH.

43
 Object Oriented Programming With Ansi & Turbo C++ By Ashok N. Kamthane, Pearson

Education.

 The Complete Reference C++ By Herbert Schildt, TMH

 The C++ Programming Language By Bjarne Stroustrup, Pearson Education.

 Object Oriented Programming in C++ By Roberrt Lafore, SAMS Publishing.

3.14 Self Assessment Questions

1. Define function. What is the advantage of using functions? Explain with example.

2. What do you mean by a function call?

3. What is the purpose of return statement?

4. Differentiate between formal and actual arguments. Give examples.

5. What is function prototype? What is the significance of using it in the program?

6. Differentiate between the following by giving suitable examples.

a) Call by value and Call by address

b) Call by value and Call by reference

7. What is inline function? Give an example.

8. What are the advantages and disadvantages of inline functions?

9. Why do you use inline function? Write some precautions for defining the inline

functions.

10. What are friend functions? Why do you need them?

11. What are friend classes? How can you define them? Explain with an example.

12. Define Pointer. How is a pointer variable declared?

44
13. What do you mean by a pointer? What are the advantages of the pointer variables in the

program?

14. Explain various operations on pointers by giving suitable examples.

15. What do you mean by this pointer? Explain the concept of this pointer by giving

suitable example.

16. Write a function to generate the Fibonacci series.

17. Write a function to find the mean of n numbers.

18. Write a function to find the sum of two matrices.

19. Write a function to find the product of two matrices.

20. Write a function to find the sum of digits of a given number.

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

format specifications to output result.

a) 12 column width

b) Right justified

c) Five digits precision

d) Filling of blank spaces with #

e) Show + before positive numbers

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++,

Dynamic Memory Management: Pointers, new and delete Operator,


Array of Pointers to Objects, this Pointer, Passing Parameters to Functions by Reference & pointers.

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

BCA - 301 (Object Oriented Programming Using C++)

Writer: Er. Matish Garg Vetter: Prof. Rajender Nath

Lesson No. 04

Arrays and Strings


UNIT – II
Structure:

4.1 Introduction

4.2 Objectives

4.3 Arrays

4.3.1 Declaration and Initialization of Array

4.3.2 Passing an array to a function

4.4 Multidimensional Arrays

4.5 Array of objects

4.6 String

4.6.1 Creating and initializing string objects

1
4.7 String Functions and Operators

4.8 Accessing and Manipulating strings

4.9 Summary

4.10 Suggested Readings

4.11 Self Assessment Questions

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

many constructors, member functions and operators to manipulate the strings.

4.2 Objectives

After going through this lesson, you will be able to:

 Describe arrays and its types.

 Understand the concept of strings.

 Describe the string functions for manipulating the strings.

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

memory space of a single dimensional array is calculated by the following formula:

Total memory space = sizeof (data type) X size of an array

4.3.1 Declaration and Initialization of Array

Like any other data element, an array has to be declared before it is used in the program. The

declaration of one-dimensional array is shown as below:

data_type A_name [ size ];

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

as A[0], A[1],………, A[4].

An array is initialized along with the declaration by placing the data elements separated by commas

with in braces. The general form is as under:

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

individual array elements such as:

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 ( );

cout << “ Enter five numbers\n”;

for ( i =0; i<5; i++ )

cin>> A[i]; // input array elements

cout << “ Elements of the given array are\n”;

for ( i =0; i<5; i++ )

cout << “A[”<< i<<“] = ” << A[i] << “\n”;

5
getch ( );

OUTPUT

Enter five numbers

8 15 16 20 25

Elements of the given array are

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.

4.3.2 Passing an array to a function

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>

float Avg_marks ( float marks[ ], int ); //Function Prototype

6
void main ( )

float marks[30], average;

int n, i ;

clrscr ( );

cout << “ Enter the numbers of students\n”;

cin>> n;

cout<< “ Enter the marks of the students\n”;

for ( i = 0; i<n; i++ )

cin>> marks[i]; // input array elements

average = Avg_marks( marks, n );

cout << “ Average marks of the class is ” << average;

getch ( );

float Avg_marks ( float marks[ ], int n)

float avg, sum = 0;

int i;

for ( i = 0; i< n; i++)

sum = sum + marks[i];

avg = sum/n;

return (avg);

7
OUTPUT

Enter the numbers of students

Enter the marks of the students

45 56 78 67 82

Average marks of the class is 65.6

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.

4.4 Multidimensional Arrays

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

general form of a multidimensional array declaration is as under:

data _type Array_name [size1] [size2]….. [size n];

Here data_type is the type of the array Array_name and n is the dimensions of the array.

A two dimensional array is declared as

int A[2] [3];

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

can be shown as below in figure 4.1:

Column 0 Column 1 Column 2

Row 0 A[0][0] A[0][1] A[0][2]

Row 1 A[1][0] A[1][1] A[1][2]

Figure 4.1 Elements of 2-dimensional array

Every element in array A is identified by an element name of the form

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.

Similarly 3-dimensional array is declared as:

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

elements this array can hold is 12.

You can initialize a multidimensional array in more than one way. Consider an example to initialize
two dimensional array.

int A[2][3] = {2, 4, 5, 8, 10, 12};

Another way to initialize this array with same array elements is as under:

int A[2][3] = { {2, 4, 5}, {8, 10, 12}};

Similarly a 3- dimensional array x is initialized as

int x[2][2][3] = {3, 4, 2, 3, 0, 3, 9, 11, 23, 12, 23,2 };

9
and the better way to initialize this array with same elements is as below:

int x[2][2][3] = { { {3, 4, 2, }, {3, 0, 3}}, {{9,11,23}, {12, 23, 2} }};

Consider an example of adding two matrices of order 2 X 3.

#include<iostream.h>

#include<iomanip.h>

#include<conio.h>

void main ( )

int x[2][3], y[2][3], z[2][3], i, j;

clrscr ( );

cout << “ Enter the elements of first matrix\n”;

for ( i = 0; i < 2; i++ )

for( j = 0; j< 3; j ++)

cin>> x[i][j];

cout << “ Enter the elements of Second matrix\n”;

for ( i = 0; i < 2; i++ )

for( j = 0; j< 3; j ++)

cin>> y[i][j];

cout<< “ Sum of two matrices \n”;

cout<< “ Resultant matrix is\n”;

for ( i = 0; i < 2; i++ )

for( j = 0; j< 3; j ++)

10
z[i][j] = x[i][j] + y[i][j];

cout<< setw(4)<<z[i][j];

cout<<endl;

getch ( );

OUTPUT

Enter the elements of first matrix

3 4 6

5 6 8

Enter the elements of Second matrix

5 0 8

2 1 1

Sum of two matrices

Resultant matrix is

8 4 14

7 7 9

4.5 Array of objects

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

categories of the vehicles. For example:

Vehicle Two_wheeler [3]; // array of two wheelers

Vehicle Four_wheeler [3]; // array of four wheelers

The array Two_wheeler [3] contains name and price information for three objects. Similarly the

next declaration maintains the same information for Four_wheelers.

Also the statement

Two_wheeler[i].getdata ( );

requests the object Two_wheeler[i] to invoke the member function getdata ( ) and reads the data of

the ith element of the array Two_wheeler.

An array of objects is stored inside the memory in the same way as a multi-dimensional array as

shown in figure 4.2

12
Name Two_wheeler [0]

Price

Name Two_wheeler [1]

Price

Name Two_wheeler [2]

Price

Figure 4.2 Storage of data elements of an array of objects

The following program illustrates the use of array of objects.

#include<iostream.h>

#include<conio.h>

class Vehicle

char Name[30];

float price;

public:

void getdata ( );

void display ( );

};

void Vehicle : : getdata ( )

13
cout<< “ Enter the name:”;

cin>>Name;

cout<< “ Enter Price:”;

cin>>price;

void Vehicle : : display ( )

cout<< “ Name:” << Name << “\n”;;

cout<< “ Price:” << price << “\n”;

void main ( )

Vehicle Two_wheeler [3];

clrscr ( );

for ( int i=0 ; i<3; i++ )

cout << “ \nDetails of Two Wheeler ” << i+1<< “\n”;

Two_wheeler [i].getdata ( );

for ( int i=0 ; i<3; i++ )

cout << “\n Two Wheeler ” << i+1<< “\n”;

Two_wheeler [i].display ( );

14
}

INPUT

Details of Two Wheeler 1

Enter the name: Cycle

Enter Price: 2500

Details of Two Wheeler 2

Enter the name: Scooter

Enter Price: 35000

Details of Two Wheeler 3

Enter the name: Motor Cycle

Enter Price: 45000

OUTPUT

Two Wheeler 1

Name: Cycle

Price: 2500

Two Wheeler 2

Name: Scooter

Price: 35000

Two Wheeler 3

Name: Motor Cycle

Price: 45000

15
In the above program, the statement

Vehicle Two_wheeler [3];

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

In C, a string is nothing but a sequence of characters and it is declared as a character array.

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.

4.6.1 Creating and initializing string objects

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

the string class are described in the table 4.1

16
Constructors Use

string ( ); To create an empty string

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

Table 4.1 String Constructors

Consider the following statements to create string objects using constructors:

string S1; // using constructor without argument to create empty string

string S2 ( “ C++ ” ); // using Null terminated string as an argument to create string

string S3 (S2); // using another string object as an argument

S1 = S2; // Assigning string objects

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:

S1 = “Ansi” + S2; // Concatenating strings

S3 += S2; // same as S3 = S3 + S2

S3 += “Program” // same as S3 = S3 + “Program”

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

cout << S1; // Display the content of string object S1

The following program illustrates the above mentioned statements of creating string objects.

17
#include< iostream>

#include<string>

int main( )

string S1; // create empty string object

string S2 ( “ Hello” ); // using string constant as an argument

string S3 ( “ India”);

S1 = S2; // Assignment using string object

cout << “ S1 = ”<< S1 << “\n”;

S1 = “ Haryana ”; // Assignment using string constant

cout << “ Now S1 = ”<< S1 << “\n”;

string S4 ( S2); // creating string object using another object

cout << “ S4 = ”<< S4 << “\n”;

S4 += S1; // (S4 = S4 + S1) appending at the end of string

cout << “ Now S4 = ”<< S4 << “\n”;

cout << “ Enter a string\n”;

cin >> S4; // reading through keyboard & delimited by blank space

cout << “ Now S4 = ”<< S4 << “\n”;

cout << “ Enter a string again \n”;

getline( cin, S4 ); // reading through keyboard with blank spaces

cout << “ Now S4 = ”<< S4 << “\n”;

S1 = S2 + S3; // Concatenating two strings

cout << “ Finally S1 = ”<< S1 << “\n”;

18
return 0;

OUTPUT

S1 = Hello

Now S1 = Haryana

S4 = Hello

Now S4 = Hello Haryana

Enter a string

Ansi C++

Now S4 = Ansi

Enter a string again

Ansi C++

Now S4 = Ansi C++

Finally S1 = Hello India

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 whole line using getline function.

4.7 String Functions and Operators

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

append ( ) Append a string to the end of another string.

assign ( ) Assigns a specified part of the string.

at ( ) Access the characters stored at specified location.

begin ( ) Returns a reference to beginning of a string.

capacity ( ) Provides total number of elements that can be stored.

compare ( ) Compare two strings.

empty ( ) Returns True if string is empty otherwise False.

end ( ) Returns a reference to the end of a string.

erase ( ) Removes the specified characters.

find ( ) Searches the specified substring in the source string.

insert ( ) Insert characters at the given location.

length ( ) Provides the total number of elements in the string.

max_size ( ) Gives the maximum possible size of a string object.

replace ( ) Replace specified characters with a given string.

resize ( ) Changes the size of a string as specified.

size ( ) Provides the number of the characters in the string.

swap ( ) Swaps two strings.

find_first_of ( ) Gives the location of first occurrence of the specified character

find_last_of ( ) Gives the location of last occurrence of the specified character

Table 4.2 String manipulating functions

20
The important overloaded operators that can be used with string objects are described in table 4.3 as

given below:

Operator Use

= Assignment

+ Joining two or more strings

+= Concatenation and assignment

== Equality

!= Not equal to

< Less than

<= Less than or equal to

> Greater than

>= Greater than or equal to

[] Subscription ( used with array)

<< Insertion operator (output)

>> Extraction operator (Input)

Table 4.3 string manipulating operators

4.8 Accessing and Manipulating strings

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( )

string S1(“ HAPPY INDEPENDENCE DAY”);

cout << “ The string is \n”;

for( int i=0; i<S1.length( ); i++)

cout<< S1.at ( i ); //display individual character

int a = S1.find(“DAY”);

cout << “ \n DAY is found at :” << a << “\n”;

int b = S1. find_first_of(‘E’);

cout << “ E is first found at : ” << b << “ \n”;

int c = S1. find_last_of(‘E’);

cout << “ E is last found at : ” << c << “ \n”;

cout << “ Retrieving and display the substring DAY \n”;

cout << S1.substr(a, 3) << “\n”;

return 0;

OUTPUT

The string is

HAPPY INDEPENDENCE DAY

DAY is found at : 20

22
E is first found at : 10

E is last found at : 18

Retrieving and display the substring DAY

DAY

Similarly the contents of the string can be modified by using the functions insert ( ), replace ( ),

erase ( ) and append ( ).

Consider the following program:

#include< iostream>

#include<string>

int main( )

string S1(“HAPPY”);

string S2(“123456”);

cout << “ The original strings are \n”;

cout << “ S1 = ”<< S1 << “\n”;

cout << “ S2 = ”<< S2 << “\n”;

// appending two strings

cout<< “ after append \n”;

S1. append (S2);

cout << “ S1 = ”<< S1 << “\n”;

// Removing 6 characters after 5th location from S1

cout<< “ Remove 6 characters from S1 \n”;

S1.erase (5, 6);

23
cout << “ after removal S1 = ”<< S1 << “\n”;

// inserting a string into another

cout<< “ insert S2 inside S1 after 3 characters \n”;

S1.insert ( 3, S2);

cout << “ after insertion S1 = ”<< S1 << “\n”;

// Replacing characters from a string

cout<< “ Replace middle 4 characters of S2 with S1 \n”;

S2.replace(1, 4,S1);

cout << “ after replacing characters S2 = ”<< S2 << “\n”;

return 0;

OUTPUT

The original strings are

S1 = HAPPY

S2 = 123456

after append

S1 = HAPPY123456

Remove 6 characters from S1

after removal S1 = HAPPY

insert S2 inside S1 after 3 characters

after insertion S1 = HAP123456PY

Replace middle 4 characters of S2 with S1

after replacing characters S2 = 1HAP123456PY6

24
Also the contents of the string objects can be compared and exchanged by the member functions

compare ( ) and swap ( ) respectively as shown in the example given below:

#include< iostream>

#include<string>

int main( )

string S1(“Look”);

string S2(“Hook”);

cout << “ The original strings are \n”;

cout << “ S1 = ”<< S1 << “\n”;

cout << “ S2 = ”<< S2 << “\n”;

// Comparing two strings

cout<< “ After Comparison \n”;

int d = S1. compare (S2);

if(d = = 0)

cout<< “ strings are identical\n”;

else

cout<< “ strings are not identical\n”;

// Swapping two strings

cout<< “ After Swapping \n”;

S1.swap(S2);

cout << “ S1 = ”<< S1 << “\n”;

cout << “ S2 = ”<< S2 << “\n”;

25
return 0;

OUTPUT

The original strings are

S1 = Look

S2 = Hook

After Comparison

strings are not identical

After Swapping

S1 = Hook

S2 = Look

4.9 Summary

 An array is a collection of homogenous data elements (elements of similar data types) which

are located in contiguous memory locations.

 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.

 Array of variables that is of type class is called array of objects.

26
 An array of objects behaves similar to any other array and usual array accessing methods are

used to access the individual elements.

 A string is nothing but a sequence of characters.

 In C, string is declared as a character array. 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.

 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.

4.10 Suggested Readings

 Object Oriented Programming With C++ By E Balagurusamy, TMH.

 Object Oriented Programming With Ansi & Turbo C++ By Ashok N. Kamthane, Pearson

Education.

 The Complete Reference C++ By Herbert Schildt, TMH

 The C++ Programming Language By Bjarne Stroustrup, Pearson Education.

 Object Oriented Programming in C++ By Roberrt Lafore, SAMS Publishing.

27
4.11 Self Assessment Questions

1. What do you mean by Array? How an array is declared and initialized?

2. Explain any three characteristics of arrays.

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.

7. What is the difference between C strings and C++ strings?

8. Describe the various overloaded operators used to manipulate the strings in C++.

9. Describe the purpose of various string functions in C++ with examples.

 begin ( )

 append ( )

 at ( )

 erase ( )

 max_size ( )

 resize ( )

 capacity ( )

 assign ( )

10. Write a program to find the product two matrices.

11. Write a program to calculate the sum of diagonal elements of 3 X 3 matrix.

28
12. Write a program to declare 2-dimensional array of characters. Store ten names in array and

display the names in ascending order.

13. Write a program to calculate the determinant of 2 X 2 matrix using pointers.

14. Write a program to sort an array of 10 integers.

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 ( ).

19. Write a program to compare two strings using relational operators.

20. Write a program to determine whether a string object is initialized or not.

21. Write a program to find the starting character of a given string.

22. Write a program to assign a sub-string from main string to another string.

23. Write a program to find the length of a given string.

29
UNIT – II
Manipulators, Friend Function, Friend Class, Arrays, Array of Objects, Passing and Returning Objects to
Functions, String Handling in C++,

Dynamic Memory Management: Pointers, new and delete Operator,


Array of Pointers to Objects, this Pointer, Passing Parameters to Functions by Reference & pointers.

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

BCA - 301 (Object Oriented Programming Using C++)

Writer: Er. Matish Garg Vetter: Prof. Rajender Nath

Lesson No. 05

Compile-Time Polymorphism
UNIT – II
Structure:

5.1 Introduction

5.2 Objectives

5.3 Operators

5.3.1 Arithmetic Operators

5.3.2 Relational Operators

5.3.3 Logical Operators

5.3.4 Bitwise Operators

5.3.5 Increment and Decrement operators

5.3.6 Conditional Operator

5.3.7 Sizeof Operator

1
5.3.8 Scope Resolution Operator

5.4 Precedence and associativity in Operators

5.5 Unary and Binary Operators

5.6 Compile-Time Polymorphism

5.6.1 Function Overloading

5.6.2 Operator Overloading

5.6.2.1 Overloading Unary Operators

5.6.2.2 Overloading Binary Operators

5.6.2.3 Operator overloading Using Friend Functions

5.7 Summary

5.8 Suggested Readings

5.9 Self Assessment Questions

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

Run-Time Compile -Time


(Dynamic) Polymorphism (Static) Polymorphism

Virtual Function Function Operator


Overloading Overloading

Figure 5.1 Types of 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.

Compile-Time Polymorphism is accomplished by overloading Functions and operators. Specifying

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.

Similarly, in operator overloading, an operator exhibits different behaviours in different instances.

In this lesson we also discuss about operators, their precedence and associativity, function

overloading and operator overloading.

5.2 Objectives

After going through this lesson, you will be able to:

 Describe different operators used in C++.

 Understand and describe the precedence and associativity of operators and their role in

computations.

 Understand Function Overloading and Operator Overloading.

 Describe and give different examples of Function Overloading and Operator Overloading.

 Perform Operator Overloading through Friend Functions.

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:

Types of Operators Symbolic Representation

Arithmetic Operators +, -, *, / and %

Relational Operators >, <, ==, >=, <= and !=

Logical Operators &&, || and !

Bitwise Operators &, |, ^, >>, << and ~

Assignment Operators =

Increment and decrement Operators ++, --

Comma Operator ,

Conditional Operator ?:

Table 5.1 Types of operators

There are some additional operators in C++, which are discussed in Table 5.2:

5
Operators Description

<< Insertion Operator

>> Extraction Operator

:: Scope Resolution Operator

: :* Pointer to member Decelerator

->* Deference pointers to pointers to class members

.* Deference pointers to class members

Delete Memory Release Operator

New Memory Allocation Operator

endl Line Feed Operator

setw Field Width Operator

sizeof Size Operator

Table 5.2 Additional Operators in C++

5.3.1 Arithmetic Operators

Arithmetic operators perform arithmetic operations such as addition, subtraction, multiplication,

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

of evaluation of operators in an expression. The parentheses force an operation or set of operations

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.

Operator Description Precedence Associativity

-, + Unary minus , Unary plus 1 (Highest) Right to Left

2 Left to Right
Multiplication, Division,
*, /, %
Modulus/Remainder operator

+, - Binary plus , Binary minus 3 Left to Right

Table 5.3 Arithmetic operators

5.3.2 Relational Operators

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

of Relational operators with associativity in the order of their precedence.

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 value of left operand is less than or


<= ( Less or
equal to the value of right operand, if yes then condition
equal to)
becomes true.

‘>’ Checks whether the value of left operand is greater than


> ( Greater
the value of right operand, if yes then condition becomes
Than)
true.

‘>=’ Checks whether the value of left operand is greater


>=( Greater than
than or equal to the value of right operand, if yes then
equal to)
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.

Table 5.4 Relational operators

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.

The precedence of relational operators is

1. <, <=, >, >= Higher Precedence

2. = =, != Lower Precedence

5.3.3 Logical Operators

Logical operators provide the ways to connect the relationships that the operands can have with one

another. Table 5.5 shows the list of logical operators.

Operator Meaning

&& Logical AND

|| Logical OR

! Logical NOT

Table 5.5 Logical Operators

The truth table of logical operators is shown in table 5.6.

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

Table 5.6 Truth Table of Logical operators

Expressions that use logical operators return 0 for false and 1 for true. Relational and logical

operators are often used together. For example

30 < 45 && 5 >= 2 is true.

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.

Operator Precedence Associativity

&& 1(Highest) Left to Right

|| 2 Left to Right

! 3 Left to Right

Table 5.7 Precedence and Associativity of Logical operators

5.3.4 Bitwise Operators

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

data types. List of bitwise operators is given in the table 5.8.

Operator Meaning

& bitwise AND

| bitwise OR

^ bitwise exclusive OR

~ One’s Complement

<< shift left

>> shift right

Table 5.8 Bitwise operators

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 complement of A = 11000101 is given by ~A=00111010.

The left shift operator shifts the bit patterns a number of bits to the left and blank spaces produced

at the right 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 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

The following program better describes the bitwise operators.

#include<iostream.h>

#include< iomanip.h>

#include<conio.h>

11
void main ( )

int x=10, y=20;

clrscr ( );

cout << “x&y = ” <<(x&y)<< “\n”;

cout << “x|y = ” <<(x|y)<< “\n”;

cout << “x^y = ” <<(x^y)<< “\n”;

cout << “~x = ” <<(~x)<< “\n”;

cout << “x<<2 = ” <<(x<<2)<< “\n”;

cout << “x>>2 = ” <<(x>>2)<< “\n”;

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 0000 0000 0000 1010 10

y 0000 0000 0001 0100 20

x&y 0000 0000 0000 0000 0

x|y 0000 0000 0001 1110 30

x^y 0000 0000 0001 1110 30

~x 1111 1111 1111 0101 65525 ( -11)

x << 2 0000 0000 0010 1000 40

x >> 2 0000 0000 0000 0010 2

Table 5.9 Binary form of bitwise operations

~x is equivalent to decimal 65525 but the range of an integer is -32768 to +32767. Therefore after

counting +32767, counter starts from -32768 and yields -11.

The precedence and associativity of bitwise operators is given in Table 5.10.

Operator Precedence Associativity

~ 1 (Highest) Right to Left

<<, >> 2 Left to Right

& 3 Left to Right

^ 4 Left to Right

| 5 Left to Right

Table 5.10 Precedence and associativity of bitwise operators

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

an expression. The pre-increment or pre-decrement operator increases or decreases the value of

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

expression. For example:

X = 5;

14
Y = -- X;

Here the value of X and Y is 4. But if you rewrite the above statement as

Y = X --;

Then the value of Y would be 5 and X would be 4.

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

after using it in the expression.

The precedence of both increment and decrement operators is same and the associativity is right to

left.

5.3.6 Conditional Operator

C++ contains a ternary operator pair ? : that replaces the if - then - else statements. The general

form is

expression 1 ? expression 2 : expression 3;

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

expression. For example

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

above statements is equivalent to the following if-else statement

a = 20;

15
if ( a > 15)

b = 50;

else

b = 60;

5.3.7 sizeof Operator

The sizeof is a unary operator which returns the size of operand in bytes. The operand may be a

variable, a constant or a data type. For example

sizeof (var);

returns the size occupied by the variable var.

Consider the following program:

#include<iostream.h>

#include< iomanip.h>

#include<conio.h>

void main ( )

clrscr ( );

cout << “size of char is ” << sizeof (char)<< “\n”;

cout << “size of int is ” << sizeof (int)<< “\n”;

cout << “size of float is ” << sizeof (float)<< “\n”;

cout << “size of double is ” << sizeof (double)<< “\n”;

getch ( );

16
OUTPUT

size of char is 1

size of int is 2

size of float is 4

size of double is 8

Here the output gives the size of different data types.

5.3.8 Scope Resolution Operator

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

value of variable m. consider the following program.

#include< istream.h>

#include<conio.h>

int x=25; // global variable

void main ( )

clrscr( );

int x=35; // local variable

cout<< “ Global x = ”<<: : x<<”\n”;

cout<< “ Local x = ”<< x <<”\n”;

getch ( );

17
}

OUTPUT

Global x = 25

Local x = 35

5.4 Precedence and associativity in Operators

The complete precedence and associativity of all the operators discussed in this lesson are given in

the table 5.11 given below.

Operator Precedence Associativity


() 1(Highest) Left to Right

sizeof ~ ++ - - ! - (unary minus) 2 Right to Left


Left to Right
* / % 3
Left to Right
+ - 4
Left to Right
<< >> 5
Left to Right
< <= > >= 6
Left to Right
== != 7
Left to Right
& 8
Left to Right
^ 9
Left to Right
| 10
Left to Right
&& 11
Left to Right
|| 12
Right to Left
?: 13
Right to Left
All assignment operators 14
Comma operator 15(Lowest) Left to Right

Table 5.11 Precedence and associativity of the operators

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

operand i.e. ‘B’ so it is a unary operator.

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

acts as the subtraction operator i.e. binary operator.

All Unary and Binary operators are listed in a Table 5.12 given below:

Operator Name Type

! Logical NOT Unary

& Address-of Unary

() Cast Operator Unary

* Pointer dereference Unary

+ Unary Plus Unary

++ Increment Unary

– Unary negation Unary

–– Decrement Unary

19
~ complement Unary

, Comma Binary

!= Inequality Binary

% Modulus Binary

%= Modulus assignment Binary

& Bitwise AND Binary

&& Logical AND Binary

&= Bitwise AND assignment Binary

* Multiplication Binary

*= Multiplication assignment Binary

+ Addition Binary

+= Addition assignment Binary

– Subtraction Binary

–= Subtraction assignment Binary

–> Member selection Binary

–>* Pointer-to-member selection Binary

/ Division Binary

/= Division assignment Binary

< Less than Binary

<< Left shift Binary

20
<<= Left shift assignment Binary

<= Less than or equal to Binary

= Assignment Binary

== Equality Binary

> Greater than Binary

>= Greater than or equal to Binary

>> Right shift Binary

>>= Right shift assignment Binary

^ Exclusive OR Binary

^= Exclusive OR assignment Binary

| Bitwise inclusive OR Binary

Bitwise inclusive OR
|= Binary
assignment

|| Logical OR Binary

Table 5.12 Unary and Binary operators

5.6 Compile-Time Polymorphism

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

and Operator overloading as shown in figure 5.2.

Compile -Time Polymorphism


(Static Binding)

Function Operator
Overloading Overloading

Figure 5.2 Compile-Time Polymorphism

5.6.1 Function 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,

rectangle and circle.

22
#include <iostream.h>

#include <conio.h>

int find_Area ( int , int );

float find_Area( double, double );

float find_Area( double )

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);

cout<< “ \n area of rectangle is ” << areaR;

cout<< “ \n area of triangle is ” << areaT;

cout<< “ \n area of circle is ” << areaC;

getch( );

int find_Area(int len , int bh)

return ( len * bh );

23
int find_Area(double bs , double ht)

return (0.5 * bs * ht );

int find_Area( double r)

return ( 3.142857 * r * r );

OUTPUT

area of rectangle is 75

area of triangle is 4.125

area of circle is 88.282853

Some precautions should be taken during function overloading:

a) Function prototypes must be declared before main ( );

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

data, should be overloaded.

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

form of an operator function is

<Return type> <classname> :: operator < operator>(argument list)

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

C++ are overloaded except the following:

 Class member access operators ( . , .*)

 Scope resolution Operator ( :: )

 Size operator (sizeof)

 Conditional operator ( ? : )

Both Unary and Binary operators can be overloaded.

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

object that calls it.

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 :

void readdata (int x, int y, int z)

a=x;

b=y;

c=z;

26
}

void show (void)

cout << a << “ ”;

cout << b << “ ”;

cout << c << “ \n ”;

void operator – ( );

};

void Unaryop :: operator – ( )

a = -a;

b = -b;

c = -c;

int main( )

clrscr( );

Unaryop U;

U. readdata ( 5 , -15, 25 );

cout << “ Before :”;

U. show ( );

-U; // invokes operator –( ) function

27
cout << “after :” ;

U. show ( );

return 0;

OUTPUT

Before : 5 -15 25

After : -5 15 -25

5.6.2.2 Overloading Binary Operators

Binary operators can be overloaded in a similar manner as unary operators.

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:

void setDimensions( double ln, double bh, double ht )

length = ln;

breadth = bh;

height = ht;

double Volume(void)

return length * breadth * height;

Box operator + (Box b) // Overload ‘+’ to add two Box objects.

Box box;

box.length = length + b.length;

box.breadth = breadth + b.breadth;

box.height = height + b.height;

return box;

};

29
int main( )

Box Box1;

Box Box2;

Box Box3;

double volume = 0.0;

Box1.setDimensions(4.0,6.0,8.0);

Box2. setDimensions(5.0,7.0,9.0);

volume = Box1.Volume( );

cout << "Volume of Box1 : " << volume <<endl;

volume = Box2.Volume();

cout << "Volume of Box2 : " << volume <<endl;

Box3 = Box1 + Box2;

volume = Box3.getVolume();

cout << "Volume of Box3 : " << volume <<endl;

return 0;

OUTPUT

Volume of Box1 : 192

Volume of Box2 : 315

Volume of Box3 : 1989

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.

5.6.2.3 Operator Overloading Using Friend Functions

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)

return length * breadth * height;

31
void setDimensions( double ln, double bh, double ht )

length = ln;

breadth = bh;

height = ht;

friend Box operator + ( Box, Box);

};

Box operator + (Box b1, Box b2) // Overload ‘+’ to add two Box objects.

Box box;

box.length = b1.length + b2.length;

box.breadth = b1.breadth + b2.breadth;

box.height = b1. height + b2.height;

return box;

int main( )

Box Box1;

Box Box2;

Box Box3;

double volume = 0.0;

Box1.setDimensions(4.0,6.0,8.0);

32
Box2. setDimensions(5.0,7.0,9.0);

volume = Box1.Volume( );

cout << "Volume of Box1 : " << volume <<endl;

volume = Box2.Volume();

cout << "Volume of Box2 : " << volume <<endl;

Box3 = operator + (Box1 , Box2); // invoking friend function

volume = Box3.getVolume();

cout << "Volume of Box3 : " << volume <<endl;

return 0;

OUTPUT

Volume of Box1 : 192

Volume of Box2 : 315

Volume of Box3 : 1989

5.7 Summary

 Polymorphism means the ability to take more than one form.

 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.

 Compile-Time Polymorphism includes function overloading and operator overloading.

33
 In Function overloading, a single function name is used to perform different tasks by using

different number and different types of arguments.

 Operator overloading is an important mechanism in C++ which defines an additional task to

an operator.

 Overloading of operators can be categorized in two types i.e. Unary operator Overloading

and Binary operator overloading.

 Some operators i.e. Class member access operators (. , .*), Scope resolution Operator ( :: ),

Size operator (sizeof), Conditional operator ( ? : ) cannot be overloaded.

 An operator is a symbol to perform specific operation on the operands.

 A unary operator requires one operand and a binary operator needs two operands whereas a

ternary operator requires three operands.

 Arithmetic operators perform arithmetic operations such as addition, subtraction,

multiplication, division etc.

 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.

 Conditional operator ? : is a ternary operator that replaces the if else statement.

 The pre-increment or pre-decrement operators first changes its operands value and then uses

it in the expression whereas post-increment or post-decrement operators firstly uses the

value and then increments or decrements it.

 Scope resolution operator is used to access the global value of variable.

 The sizeof operator returns the size of operand in bytes.

34
 A non-member function called friend function can access to the private members of a class

by declaring it friend to the class whose private members are to be accessed.

 Friend function of a class can be a member function of another class.

 Operators may be overloaded by using Friend functions also.

5.8 Suggested Readings

 Object Oriented Programming With C++ By E Balagurusamy, TMH.

 Object Oriented Programming With Ansi & Turbo C++ By Ashok N. Kamthane, Pearson

Education.

 The Complete Reference C++ By Herbert Schildt, TMH

 The C++ Programming Language By Bjarne Stroustrup, Pearson Education.

 Object Oriented Programming in C++ By Roberrt Lafore, SAMS Publishing.

5.9 Self Assessment Questions

1. What do you mean by Polymorphism?

2. What is the difference between Compile-Time Polymorphism and Run-Time

Polymorphism?

3. What is Function Overloading? What are the rules for defining overloaded functions?

4. What is an operator? Describe different types of operators available in C++.

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?

7. What is the difference between unary and binary operators?

8. Describe the various arithmetic operators and the rules associated with their use in C++.

9. What are relative operators?

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.

13. Explain the conditional operator by giving 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?

16. What is the significance of keyword ‘operator’ in operator overloading?

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.

19. List the operators that cannot be overloaded.

20. What is difference between function overloading and operator overloading?

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.

24. Write a program to evaluate the following expressions:

a) ++ x * ++ y b) ++ x + ++y c) x ++ + ++ y d) x++ * y++

Where x and y are integer variables.

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

and float number to ASCII string.

28. Write a program to overload the function ‘volume’ which returns volume of different shapes

like cuboid, sphere and cylinder.

29. Write a program to overload ‘ > ’ operator to display the largest object out of the two

objects.

30. Write a program to overload ‘ = = ’ and compare two objects.

31. Write a program to overload ++ and - - operators.

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.

34. Write a program to concatenate two strings by overloading ‘ + ’ operator.

37
UNIT – II
Manipulators, Friend Function, Friend Class, Arrays, Array of Objects, Passing and Returning Objects to
Functions, String Handling in C++,

Dynamic Memory Management: Pointers, new and delete Operator,


Array of Pointers to Objects, this Pointer, Passing Parameters to Functions by Reference & pointers.

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

BCA - 301 (Object Oriented Programming Using C++)

Writer: Er. Matish Garg Vetter: Prof. Rajender Nath

Lesson No. 06

Dynamic Polymorphism
UNIT – III
Structure:

6.1 Introduction

6.2 Objectives

6.3 Static and Dynamic Binding

6.4 Pointer to Objects

6.5 Virtual Functions and their Need

6.5.1 Rules for Virtual Functions

6.6 Pure Virtual Function

6.7 Abstract Classes

1
6.8 Constructors and Virtual Functions

6.9 Destructors and Virtual Functions

6.10 Summary

6.11 Suggested Readings

6.12 Self Assessment Questions

2
6.1 Introduction

Polymorphism is an important feature of Object Oriented Programming. As earlier discussed, it is

categorized in two types: Compile-Time (Static) Polymorphism and Run-Time (Dynamic)

Polymorphism. The compile-time polymorphism or static binding is accomplished by function

overloading and operator overloading whereas run-time polymorphism or dynamic binding is

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,

the dynamic Polymorphism using virtual function is discussed.

6.2 Objectives

After going through this lesson, you will be able to:

 Understand the use of pointer to objects.

 Describe the difference between static and dynamic binding.

 Understand the concept of Virtual function and their needs.

 Understand the use of constructors and destructors with virtual functions.

6.3 Static Binding and Dynamic Binding

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

Run-Time Compile -Time


(Dynamic Binding) (Static Binding)

Virtual Function Function Operator


Overloading Overloading

Figure 6.1 Types of Polymorphism

6.4 Pointer to objects

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

< Class name> * Object pointer;

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

Object pointer -> member function ( );

Let us take an example.

# include < iostream.h>

# include < constream.h>

class Employee

int Emp_id;

float salary;

public:

void getdata( int e, float s)

Emp_id = e;

salary = s;

void showdata ( )

5
{

cout << “ Employee id : ” << Emp_id;

cout<< “ \n Salary : Rs.” << salary;

};

void main ( )

clrscr ( );

Employee E;

Employee *Etr = &E;

Etr -> getdata (234, 20000);

Etr -> showdata ( );

OUTPUT

Employee id : 234

Salary : Rs. 20000

In this program, Etr is the object pointer which refers to the object E of the class Employee. The

statements using arrow operator and object pointer

Etr -> getdata (234, 20000);

Etr -> showdata ( );

are equivalent to the normal access using dot operator and the object i.e.

E . getdata (234, 20000);

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.

# include < iostream.h>

# include < constream.h>

class Base

int a ;

public:

Base ( )

a = 20;

void show ( )

cout<< “ \n a = ” << a;

7
};

class Derived : public Base

int b;

public:

Derived ( )

b =25;

void show ( )

cout << “\n b = ” << b ;

};

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

operator must be used. But here polymorphism is not achieved.

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

defined and it refers to all the derived class objects.

# include < iostream.h>

# include < constream.h>

class Base

int a ;

public:

Base ( )

a = 20;

void show ( )

9
cout<< “ \n a = ” << a;

};

class Derived : public Base

int b;

public:

Derived ( )

b =25;

void show ( )

cout << “\n b = ” << b ;

};

void main ( )

clrscr ( );

Base S, *ptr;

Derived D;

ptr = &S

10
ptr -> show ( );

ptr = &D

ptr -> show ( );

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.

It is achieved only by using the Virtual Functions.

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

virtual function is like this:

virtual < Return type> < Function name> ( parameters)

………………

………………

Let us elaborate the previous example by using the virtual functions.

11
# include < iostream.h>

# include < constream.h>

class Base

int a ;

public:

Base ( )

a = 20;

virtual void show ( ) // virtual function

cout<< “ \n a = ” << a;

};

class Derived : public Base

int b;

public:

Derived ( )

b =25;

12
}

void show ( )

cout << “\n b = ” << b ;

};

void main ( )

clrscr ( );

Base S, *ptr;

Derived D;

ptr = &S

ptr -> show ( );

ptr = &D

ptr -> show ( );

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.

# include < iostream.h>

# include < constream.h>

class Shape

protected:

double len , bd ;

public:

void get_data( double x, double y)

len = x ;

bd = y ;

virtual void show_area ( ) // empty virtual function

14
};

class Rectangle : public Shape

public:

void show_area ( )

cout << “\n area of rectangle = ” << len *bd ;

};

class Triangle : public Shape

public:

void show_area ( )

cout << “\n area of triangle = ” << 0.5 * len * bd ;

};

void main ( )

clrscr ( );

Rectangle R;

15
R . get_data (5.6, 7.5)

Triangle T;

T. get_data ( 5.0, 9.5)

Shape *area[2];

area [0] = & R;

area [1] = & T;

area [0] -> show_area ( );

area [1] -> show_area ( );

OUTPUT

area of rectangle = 42

area of triangle =23.75

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.

6.5.1 Rules for Virtual Functions

Some points should be remembered while using the virtual functions.

I. The virtual functions must be member functions of class.

II. The virtual functions are accessed by using object pointers.

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.

V. A virtual function can be declared as friend function of another class.

VI. The virtual function must be defined in the public section of the class.

VII. Virtual functions can return values like other ones.

VIII. The prototype of virtual functions in the base class and derived class should be same.

IX. Arithmetic operations cannot be performed with base class pointer.

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

base class function as in normal inheritance case.

6.6 Pure Virtual Function

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

the base class. The syntax of declaration of pure virtual function is

virtual void < Function name > ( ) = 0;

For example

17
virtual void Show ( ) = 0;

The function Show ( ) is a pure virtual function. The assignment to zero indicates that the function

is a pure virtual function and it will not have a definition.

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

made pure virtual function.

# include < iostream.h>

# include < constream.h>

class Base

protected:

int a ;

public:

Base ( )

a = 20;

virtual void Show ( ) = 0; // Pure virtual function

};

class Derived : public Base

18
int b;

public:

Derived ( )

b =25;

void Show ( )

cout << “\n a = ” << a << “\n b = ” << b;

};

void main ( )

clrscr ( );

Base *ptr;

Derived D;

ptr = &D

ptr -> Show ( );

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.

6.7 Abstract Classes

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

following points must be remembered:

I. An abstract class can be used as a base class.

II. Objects of abstract class cannot be declared.

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

take an example of such class.

# include < iostream.h>

# include < constream.h>

class Debug

public:

20
virtual void show ( )

cout << “ \n show ( ) function is not defined here”;

};

class X : public Debug

int x;

public:

X()

x =5;

void show ( )

cout << “\n in class X x = ” << x;

};

class Y : public Debug

int y;

21
public:

Y()

y = 15;

};

void main ( )

clrscr ( );

X x1;

Y y1;

x1. show ( );

y1. show ( );

OUTPUT

in class X x = 5

show ( ) function is not defined here

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

function is executed rather than that of base class.

Consider this program

# include < iostream.h>

# include < constream.h>

class X

int a;

public:

X()

a = 5;

virtual void display( )

cout << “\n a = ” << a;

};

23
class Y : public X

int b;

public:

Y( )

b = 15;

X *x ;

x = this;

x -> display ( );

void display( )

cout << “\n b = ” << a;

};

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 ( ).

6.9 Destructors and Virtual Functions

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

program illustrates this.

# include < iostream.h>

# include < constream.h>

class X //base class

public:

X()

cout<< “ \n constructor of base class X”;

25
}

virtual ~X ( )

cout<< “ \n destructor of base class X”;

};

class Y : public X //derived class

public:

Y()

cout<< “ \n constructor of derived class Y”;

~Y ( )

cout<< “ \n destructor of derived class Y”;

};

void main ( )

clrscr ( );

X *ptr;

ptr = new Y;

26
delete ptr;

OUTPUT:

constructor of base class X

constructor of derived class Y

destructor of derived class Y

destructor of base class X

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

the destructor of base class is executed.

6.10 Summary

 Run-time polymorphism also known as dynamic binding is the link between function

call and actual function during the execution of the program.

 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 compiler to perform early binding.

 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

of the base class.

 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

class is called pure virtual function.

 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.

 Constructors cannot be declared as virtual. However it is possible to invoke a virtual

function using constructor.

 Destructors may be declared as virtual and called as virtual destructors.

 Virtual destructors are implemented in the same way like virtual functions.

6.11 Suggested Readings

 Object Oriented Programming With C++ By E Balagurusamy, TMH.

 Object Oriented Programming With Ansi & Turbo C++ By Ashok N. Kamthane,

Pearson Education,

 The Complete Reference C++ By Herbert Schildt, TMH

6.12 Self Assessment Questions

1. Define run-time polymorphism.

28
2. What is the difference between static and dynamic binding?

3. What do you mean by pointer to objects?

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.

7. Where do we use virtual functions? Give its applications.

8. What are abstract classes? How can we create them?

9. What is the difference between abstract classes and concrete classes?

10. Describe the rules for using the virtual functions.

11. Explain virtual destructor with an example.

12. Write a program to invoke member functions of base class and derived classes using

pointer of base class.

13. Write a program to invoke a virtual function using constructor.

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

derived classes book & tape for storing respective details.

29
DIRECTORATE OF DISTANCE EDUCATION

KURUKSHETRA UNIVERSITY,

KURUKSHETRA-136119

BCA III

BCA - 301 (Object Oriented Programming Using C++)

Writer: Er. Matish Garg Vetter: Prof. Rajender Nath

Lesson No. 07

Inheritance in C++
UNIT – IV

Structure:

7.1 Introduction

7.2 Objectives

7.3 Inheritance

7.3.1 Defining Subclass

7.3.2 Derivation Rules

7.4 Types of Inheritance

7.4.1 Single Inheritance

7.4.2 Multilevel Inheritance

1
7.4.3 Multiple Inheritance

7.4.4 Hierarchical Inheritance

7.4.5 Hybrid Inheritance

7.5 Constructors and Destructors in Inheritance

7.6 Summary

7.7 Suggested Readings

7.8 Self Assessment Questions

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

After going through this lesson, you will be able to:

 Understand the concept of reusability by using inheritance.

 Describe how to inherit new classes from the base one.

 Describe different types of inheritance.

 Understand the role of constructors and destructors in Inheritance.

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.

7.3.1 Defining Subclass

A subclass (or derived class) can be inherited from a superclass (or base class).

The syntax for deriving a subclass from a superclass is as follows:

class <Subclass Name> : <access-specifier> < Superclass Name>

......

};

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.

7.3.2 Derivation Rules

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>

# include < constream.h>

class BS

int x = 15;

public:

void showx( )

cout<< “member of base class :” << x;

};

class DR : public BS

int y = 30;

public:

void showy( )

cout<< “ member of derived class :” << y;

};

void main ( )

5
clrscr ( );

DR d;

d . showx ( );

d. showy ( );

OUTPUT

member of base class :15

member of derived class :30

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

private members of the derived class.

For example:

# include < iostream.h>

# include < constream.h>

class BS

int x = 15;

public:

void showx( )

6
{

cout<< “member of base class :” << x;

};

class Dr : private Bs

int y = 30;

public:

void showy( )

showx ( );

cout<< “ member of derived class :” << y;

};

void main ( )

clrscr ( );

Dr d;

d. showy ( );

7
OUTPUT

member of base class :15

member of derived class :30

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:

# include < iostream.h>

# include < constream.h>

class BS

protected:

int x = 15;

public:

void showx( )

cout<< “member of base class :” << x;

8
};

class DR : protected BS

int y = 30;

public:

void showy( )

cout<< “member of base class in derived :” << x;

cout<< “ member of derived class :” << y;

};

void main ( )

clrscr ( );

DR d;

d. showy ( );

OUTPUT

member of base class in derived :15

member of derived class :30

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:

S. No. Base Class Access mode Derived Class access mode

Private Public Protected

1 Private Not inherited Not inherited Not inherited

2 Public Private Public Protected

3 Protected Private Protected Protected

Table 7.1 Access Specifiers

7.4 Types of Inheritance

The process of inheritance may be a simple one or complex. This depends on the following points:

 Number of base classes

 Number of derived classes

10
 Mechanism of derivation

On the basis of above points, the inheritance is classified as follows:

I. Single Inheritance

II. Multilevel Inheritance

III. Multiple Inheritance

IV. Hierarchical Inheritance

V. Hybrid Inheritance

7.4.1 Single 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)

Figure 7.1 Single inheritance

Let us take a simple example to illustrate single inheritance:

11
# include < iostream.h>

# include < constream.h>

class Employee

protected:

int Emp_id;

};

class Salary : public Employee

float Amt;

public:

void get_data( int e, float s )

Emp_id = e;

Amt = s;

void show_salary ( )

cout << “ Salary of Employee id ” << Emp_id<< “ is Rs. ”<<Amt;

};

void main ( )

12
clrscr ( );

Salary s1;

s1 . get_data (234, 20000);

s1. show_salary ( );

OUTPUT

Salary of Employee id 234 is Rs. 20000

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

get_data ( ) and show_salary ( ).

7.4.2 Multilevel Inheritance

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

can be extended to any number of levels.

The class definitions in multilevel inheritance are as under:

class < Class Name1> // Base class

13
…………

};

class < Class Name 2> : <access specifier> < Class Name1>

{ // < Class Name 2> derived from < Class Name1>

…………..

};

class < Class Name 3> : <access specifier> < Class Name2>

{ // < Class Name 3> derived from < 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)

Figure 7.2(a) Multilevel inheritance

14
Base Class
(Shape)

Intermediate
Base Class
(Ellipse)

Derived Class
(Circle)

Figure 7.2(b) Multilevel inheritance

The program describing the multilevel inheritance is given below:

# include < iostream.h>

# include < constream.h>

class Shape

protected:

char sname[25];

public:

void get_ShapeName ( )

cout << “ Enter the name of shape \n”;

15
cin>> sname;

void show_ShapeName( )

cout << “ Shape Name : ” << sname ;

};

class Elliplse : public Shape

protected:

float Ra, Rb, Area ;

public:

void get_Radius ( float a, float b = 0)

Ra = a;

Rb = b;

void show_ElpArea ( )

Area = 3.142 * Ra * Rb;

cout << “\n Area of ” <<sname<< “ :”<< Area;

16
};

class Circle : public Ellipse

public:

void show_CrArea ( )

Area = 3.142 * Ra * Ra;

cout << “\n Area of ” <<sname<< “ :”<< Area;

};

void main ( )

clrscr ( );

Shape S1;

S1. get_ShapeName ( );

S1. get_Radius ( 6 );

S1. show_CrArea ( );

OUTPUT

Enter the name of shape

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.

7.4.3 Multiple 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

both the parents. The general syntax of derived class is as under:

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).

Base Class 1 Base Class 2


(Father) (Mother)

Derived Class
(Child)

Figure 7.3(a) Multiple inheritance

Base Class 1 Base Class 2


(Red) (Yellow)

Derived Class
(Orange)

Figure 7.3 (b) Multiple inheritance

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

resulting colour after their combination.

# include < iostream.h>

# include < constream.h>

class Red

public:

void Red ( )

cout << “ Red + ” ;

};

class Yellow

public:

void Yellow ( )

cout << “ Yellow ” ;

};

20
class Orange: public Red, public Yellow

public:

void Orange ( )

cout << “ = Orange ” ;

};

void main ( )

clrscr ( );

Orange O1;

OUTPUT

Red + Yellow = Orange

In this program, object of derived class Orange is declared. When object is declared constructors are

executed from base classes to derived class.

7.4.4 Hierarchical Inheritance

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)

Derived Class Derived Class Derived Class


(Saving Account) (Current (Fixed Deposit)
Account)

Figure 7.4 Hierarchical Inheritance

Let us take an example of hierarchical inheritance with a base class Account and three derived

classes Saving_Account, Current_Account and Fixed_Deposit.

# include < iostream.h>

# include < constream.h>

class Account

protected:

22
char name[25 ] ;

public:

void get_name ( )

cout << “ enter the name of account holder\n”;

cin>> name;

void show_name ( )

cout << “ Name : ” << name ;

};

class Saving_Account: public Account

int Acc_no;

float Amount ;

public:

void get_data ( int a, float b)

get_name( );

Acc_no = a;

Amount = b;

23
}

void show_data ( )

show_name ( );

cout << “\n Saving Acc:”<<Acc_no << “Balance:”<<Amount ;

};

class Fixed_Account: public Account

int Acc_no;

float Amount ;

public:

void get_data ( int a, float b)

get_name( );

Acc_no = a;

Amount = b;

void show_data ( )

24
show_name ( );

cout << “\n Fixed Deposit:”<<Acc_no << “Balance:”<<Amount;

};

class Current_Account: public Account

int Acc_no;

float Amount ;

public:

void get_data ( int a, float b)

get_name( );

Acc_no = a;

Amount = b;

void show_data ( )

show_name ( );

cout << “\n Current Acc:”<<Acc_no << “Balance:”<<Amount;

};

25
void main ( )

clrscr ( );

Saving_Account s1;

Current_Account c1;

Fixed_Account f1;

s1. get_data(32560, 8190.0);

c1. get_data(01560, 29150.0);

f1. get_data(00630, 50000.0);

s1. show_data( );

c1. show_data( );

f1. show_data( );

OUTPUT

Name : Ram

Saving Acc: 32560 Balance: 8190.0

Name : sham

Current Acc: 01560 Balance: 29150.0

Name : tom

Fixed Deposit: 00630 Balance: 50000.0

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.

7.4.5 Hybrid Inheritance

Hybrid inheritance is the combination of two or more types of inheritances such as single

inheritance, multiple inheritance, multilevel inheritance or hierarchical inheritance. The examples of

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

base class Area and base class Height.

Base Class 1 Base Class 2


(Length) (Breadth)

Intermediate Base Base Class 3


Class (Area) (Height)

Derived Class
(Volume)

Figure 7.5(a) Hybrid Inheritance

27
Let us take a program to implement the above example.

# include < iostream.h>

# include < constream.h>

class Length

float len ;

public:

float get_Length ( )

cout << “ Enter the Length\n”;

cin>> len;

return len;

};

class Breadth

float bd ;

public:

float get_Breadth( )

cout << “ Enter the Breadth\n”;

28
cin>> bd;

return bd;

};

class Area : public Length, public Breadth

protected:

float Area ;

public:

void Area ( )

Area = get_Length( ) * get_Breadth( ) ;

void show_Area ( )

cout << “\n Area : ” << Area ;

};

class Height

float ht;

public:

29
float get_Height( )

cout << “ Enter the Height\n”;

cin>> ht;

return ht;

};

class Volume : public Area , public Height

float Vol ;

public:

void display_Volume ( )

Vol = Area * get_Height( );

cout << “\n Volume : ”<< Vol;

};

void main ( )

clrscr ( );

Volume V1;

V1. display_Volume ( );

30
OUTPUT

Enter the Length

Enter the Breadth

Enter the Height

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

is the combination of multilevel and multiple inheritances.

31
Base Class 1
(Student)

Base Class 3 Base Class 2 Base Class 4


(Cultural) (Test) (Sports)

Derived Class
(Result)

Figure 7.5(b) Hybrid Inheritance

The program given below shows hybrid inheritance by implementing the above example.

# include < iostream.h>

# include < constream.h>

class Student

protected:

int Rollno ;

public:

32
void get_no ( )

cout << “ enter the rollno of the student\n”;

cin>> Rollno;

void show_no ( )

cout << “Roll No.” << Rollno ;

};

class Test : public Student

protected:

float marks1, marks2 ;

public:

void get_marks ( float a, float b)

marks1 = a;

marks2 = b;

void show_marks ( )

33
cout << “\n marks in subject 1 :” << marks1 ;

cout << “\n marks in subject 2 :” << marks2 ;

};

class Sports

Protected:

float s_score ;

public:

void get_sscore( float s )

s_score = s;

void show_sscore( )

cout << “ \nsports wt: ”<<s_score;

};

class Cultural

protected:

float c_score ;

34
public:

void get_cscore( float c )

c_score = c;

void show_cscore( )

cout << “ \ncultural wt: ”<<c_score;

};

class Result : public Test , public Sports, public Cultural

float total ;

public:

void display_result ( )

total = marks1 + marks2 + s_score + c_score;

show_no ( );

show_marks ( );

show_sscore( );

show_cscore( );

cout << “\n Total Marks : ”<< total;

35
};

void main ( )

clrscr ( );

Result st1;

st1. get_no ( );

st1. get_marks(67.0, 81.0);

st1. get_sscore(6);

st1. get_cscore(7);

st1. display_result ( );

OUTPUT

enter the rollno of the student

12

Rollno 12

marks in subject 1 : 67.0

marks in subject 2 : 81.0

sports wt: 6

cultural wt: 7

Total Marks : 161

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

object of class Result.

7.5 Constructors and Destructors in Inheritance

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.

# include < iostream.h>

# include < constream.h>

class X // base class

37
public:

X()

cout<< “ \n constructor of base class X”;

~X ( )

cout<< “ \n destructor of base class X”;

};

class Y //base class

public:

Y()

cout<< “ \n constructor of base class Y”;

~Y ( )

cout<< “ \n destructor of base class Y”;

};

class Z : public X, public Y //derived class

38
{

public:

Z()

cout<< “ \n constructor of derived class Z”;

~Z ( )

cout<< “ \n destructor of derived class Z”;

};

void main ( )

clrscr ( );

Z obj; // object of derived class

OUTPUT

constructor of base class X

constructor of base class Y

constructor of derived class Z

destructor of derived class Z

destructor of base class Y

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

destructors are executed in the reverse order.

7.6 Summary

 Inheritance allows the programmer to reuse the previously defined classes.

 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.

 The object of derived class can access not only its own members but also the members of the

base class.

 C++ supports three access specifiers: private, public and protected.

 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.

 In multilevel inheritance a class is derived from another derived 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.

 Hybrid inheritance is the combination of two or more types of inheritances.

 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.

7.7 Suggested Readings

 Object Oriented Programming With C++ By E Balagurusamy, TMH.

 Object Oriented Programming With Ansi & Turbo C++ By Ashok N. Kamthane, Pearson

Education.

 The Complete Reference C++ By Herbert Schildt, TMH

 The C++ Programming Language By Bjarne Stroustrup, Pearson Education.

 Object Oriented Programming in C++ By Roberrt Lafore, SAMS Publishing.

7.8 Self Assessment Questions

1. What is inheritance? Define various types of inheritances with examples.

2. What do you mean by base class and derived class?

3. What do you mean by Access specifiers? Describe their use in inheritance.

4. What is the difference between private and protected access specifier?

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.

7. Explain hierarchical inheritance with examples.

8. Explain hybrid inheritance with examples.

9. Explain the role of constructors in inheritance with suitable 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

income tax slab.

12. Write a program to find out the interest on the amount deposited by the customers in the

saving accounts and current accounts in a bank.

13. Write a program to calculate the bill for electricity. Read the initial and final reading for the

month and take rate slabs of units as per convenience.

14. Write a program to make a list of staff members of a college and arrange them in order of

their ranks or designations.

42
UNIT – IV
Different Forms of Inheritance – Single, Multiple, Multilevel, Hierarchical and Multipath Inheritance
Roles of Constructors and Destructors in Inheritance.

Genericity in C++: Templates in C++, Function templates, Class templates in C++.


Exception Handling in C++: try, throw and catch;

Introduction to files handling in C++

DIRECTORATE OF DISTANCE EDUCATION

KURUKSHETRA UNIVERSITY,

KURUKSHETRA-136119

BCA III

BCA - 301 (Object Oriented Programming Using C++)

Writer: Er. Matish Garg Vetter: Prof. Rajender Nath

Lesson No. 08

Genericity and Exception Handling in C++


UNIT – IV
Structure:

8.1 Introduction

8.2 Objectives

8.3 Class Templates

8.3.1 Class Templates with Multiple Parameters

8.4 Function Templates

8.4.1 Function Templates with Multiple Parameters

8.4.2 Member Function Templates

8.5 Exception Handling

1
8.5.1 Exception Handling Mechanism

8.5.2 Multiple catch Statements

8.5.3 Catching Multiple Exceptions

8.5.4 Rethrowing Exceptions

8.5.5 Restricting Exceptions

8.6 Summary

8.7 Suggested Readings

8.8 Self Assessment Questions

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

After going through this lesson, you will be able to:

 Understand the concept of generic programming.

 Describe the use of class templates and function templates in programming.

 Understand the concept of Exception handling.

3
 Describe the implementation of Exception handling mechanism to handle run time errors.

8.2 Class Templates

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

of template type. The general syntax for class template is as under:

template < class T >

class class_ name

Class members and functions

………………………………

};

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

displays different values of different data types by using templates.

# include < iostream.h>

# include < conio.h>

template < class T>

class Number

4
public:

Number ( T value )

cout<< “ Entered Number is ” <<value << “\n”;

};

void main ( )

clrscr( );

Number <int> I (35);

Number <char> I (‘N’);

Number <float> I (65.05);

OUTPUT

Entered Number is 35

Entered Number is N

Entered Number is 65.05

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:

template < class T1, class T2)

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

different data types using templates.

# include < iostream.h>

# include < conio.h>

template < class T1, class T2>

class Largest

T1 Val1;

T2 Val2;

public:

6
Largest ( T1 x, T2 y )

Val1 = x;

Val2 = y;

void Show_result( )

cout<<“\nLarger value is”<< Val1 > Val2 ? Val1: Val2;

};

void main ( )

clrscr( );

Largest <int, float> L1 (35 , 56.75);

Largest <char , char> L2 (‘N’, ‘P’);

Largest <floa , double> L3(65.05, 45.75);

L1. Show_result ( );

L2. Show_result ( );

L3. Show_result ( );

OUTPUT

Larger value is 56.75

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.

8.3 Function Templates

Similar to class templates, function templates can be defined to create a number of functions with

different argument types. The general syntax is

template < class T >

returntype Function_Name ( T arg)

………………..

// 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,

char, float and double.

Let us reconsider the previous example of class template and elaborate it with function templates.

# include < iostream.h>

# include < conio.h>

8
template < class T>

Number ( T value )

cout<< “ Entered Number is ” <<value << “\n”;

void main ( )

clrscr( );

Number (35);

Number (‘N’);

Number (65.05);

OUTPUT

Entered Number is 35

Entered Number is N

Entered Number is 65.05

Here the function Number ( ) has one argument ‘value’ of template type T and it is used to display

numbers of different data types.

8.3.1 Function Templates with Multiple Parameters

Functions can use arguments of more than one template type by declaring more than one generic

data types in the template statement. The general syntax is

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

returntype Function_Name ( T1 arg1, T2 arg2, …….)

………………..

// Function body

where generic data types are separated by comma.

Let us take an example to display different data type values.

# include < iostream.h>

# include < conio.h>

template < class T1, class T2>

Number ( T1 value1, T2 value2 )

cout<< “Entered Numbers are ” <<value1 << “ ”<<value2<<“\n”;

void main ( )

clrscr( );

Number (35, “RAM”);

Number (‘N’, 67.75);

Number (65.05, 4534);

10
}

OUTPUT

Entered Number are 35 RAM

Entered Number are N 67.75

Entered Number are 65.05 4534

8.3.2 Member Function Templates

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:

template < class T>

return_ type Class_Name < T> : : Function_Name ( arg_list )

…………….

// function body

……………..

Let us take an example:

# include < iostream.h>

# include < conio.h>

11
template < class T>

class Number

public:

Number ( T value );

};

template < class T>

Number < T > : : Number ( T value )

cout<< “ Entered Number is ” <<value << “\n”;

void main ( )

clrscr( );

Number <int> I (35);

Number <char> I (‘N’);

Number <float> I (65.05);

OUTPUT

Entered Number is 35

Entered Number is N

Entered Number is 65.05

12
In the above program, the constructor function Number ( ) is defined outside the class.

8.5 Exception Handling

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:

I. Identify the problem (hit the exception).

II. Notify that an error has occurred (throw the exception).

III. Accept the error message (catch the exception).

IV. Take corrective actions (handle the exception).

8.5.1 Exception Handling Mechanism

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

generate the exceptions. This block of statements is known as try block.

ii. throw: When an exception is identified, it is thrown by using a statement throw. The throw

statement is written inside the try block.

iii. catch: the keyword catch defines the catch block which catches and handles the exception

thrown by the throw statement inside the try block.

13
try block

Identifies and throws an exception

Exception object

catch block

Catches and handles the exception

Figure 8.1 Exception handling mechanism

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.

The general form of statements is shown in figure 8.2.

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

{ …………………

…………………

throw( exception); // throws exception

…………………

catch( type arg) // catches exception

…………………

…………………

…………………

……………………………..

Figure 8.2 try, throw and catch statements

Let us take a program that shows the concept of exception handling.

# include < iostream.h>

# include < conio.h>

int main ( )

int m,n;

15
cout << “ enter the values\n”;

cin>> m;

cin>> n;

try

if ( n != 0)

cout << “ Result ( m/n) =” << m/n<<”\n”;

else

throw (x); // throws int object

catch( int e) // catches an exception

cout<< “ Exception handled; n = ” << n << “\n”;

return 0;

OUTPUT

enter the values

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

uses int type argument and displays appropriate message.

8.5.2 Multiple catch Statements

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( type1 arg)

// catch block 1

catch( type2 arg)

// catch block2

………………….

17
………………….

catch( type1 arg)

// 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

after the last catch block. Let us take an example.

# include < iostream.h>

# include < conio.h>

void Number ( int value)

try

if ( value = = 0) throw ‘x’; //char

else

if ( value > 0) throw x; // int

else

if ( value < 0) throw 1.0; // double

cout<< “ end of try block\n”;

18
catch (char ch)

cout<< “ caught a null value\n”;

catch ( int m)

cout<< “ caught a positive value\n”;

catch ( double d)

cout<< “ caught a negative value\n”;

cout<< “ end of try-catch block\n”;

void main ( )

clrscr ( );

Number ( 7 );

Number ( 0);

Number ( -2 );

OUTPUT

caught a positive value

19
end of try-catch block

caught a null value

end of try-catch block

caught a negative value

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.

8.5.3 Catching Multiple Exceptions

It is possible to define a single catch block to handle all possible types of exceptions. In such

situation the syntax of catch block is as under:

catch ( …. )

// statements for handling all exceptions

The previous example can be handled using single catch block.

# include < iostream.h>

# include < conio.h>

void Number ( int value)

20
{

try

if ( value = = 0) throw ‘x’; //char

else

if ( value > 0) throw x; // int

else

if ( value < 0) throw 1.0; // double

cout<< “ end of try block\n”;

catch (……)

cout<< “ caught an exception\n”;

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

catch blocks, single catch block is defined here.

8.5.4 Rethrowing Exceptions

Sometimes an exception received by the catch block is passed again to another exception handler.

This is known as rethrowing of exception. The syntax used is

throw ;

The above throw statement is used without any argument.

For example:

# include < iostream.h>

# include < conio.h>

void Division ( int x, int y )

cout << “ inside function\n”

try

if ( y = = 0)

22
throw y; // int

else

cout<< “ division = ” << x/y << “\n”;

catch ( int y)

cout<< “ divide by zero inside function\n”;

Throw;

cout<< “ End of function\n”;

int main ( )

cout<< “ inside main \n”;

try

Division ( 20 , 0 );

catch( int e) // catches an exception

cout<< “ caught divide by zero inside main\n ”;

23
cout<< “ End of main ( ) function\n”;

return 0;

OUTPUT

inside main

inside function

divide by zero inside function

caught divide by zero inside main

End of main ( ) function

In the above program the catch block inside the function accepts the exception and throws again

using the statement throw without any argument.

8.5.5 Restricting Exceptions

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:

Return_type Function_Name ( arg-list) throw (type-list)

………………….

…………………

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

throwing any exception by using empty type-list. That is

throw ( ) //Empty list

let us take an example

# include < iostream.h>

# include < conio.h>

void Number ( int value) throw( int, char, double)

if ( value = = 0) throw ‘x’; //char

else

if ( value > 0) throw x; // int

else

if ( value < 0) throw 1.0; // double

int main ( )

try

Number (0);

25
catch (char ch)

cout<< “ caught a null value\n”;

catch ( int m)

cout<< “ caught a positive value\n”;

catch ( double d)

cout<< “ caught a negative value\n”;

return 0;

OUTPUT

caught a null value

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 templates used with classes are called class templates.

 The main advantages of using templates are that it decreases the source code and hence

require less time.

 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

by zero or running out of the memory.

 Exception handling is a mechanism that provides resources to identify and report an

exceptional circumstance in order to take proper action.

 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 C++ By E Balagurusamy, TMH.

 Object Oriented Programming With Ansi & Turbo C++ By Ashok N. Kamthane, Pearson

Education.

 The Complete Reference C++ By Herbert Schildt, TMH

 The C++ Programming Language By Bjarne Stroustrup, Pearson Education.

 Object Oriented Programming in C++ By Roberrt Lafore, SAMS Publishing.

8.8 Self Assessment Questions

1. Define generic programming. How it is implemented in C++?

2. Define class templates.

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.

6. Explain class template with multiple parameters. Give an example.

7. What are the advantages and disadvantages of templates?

8. What do you mean by exception handling?

9. Explain exception handling mechanism.

28
10. Describe the role of try, throw and catch keywords in exception handling.

11. What do you mean by rethrowing an exception? Explain with an example.

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.

20. Write a program to explain the concept of multiple catch statements.

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.

Genericity in C++: Templates in C++, Function templates, Class templates in C++.


Exception Handling in C++: try, throw and catch;

Introduction to files handling in C++

DIRECTORATE OF DISTANCE EDUCATION

KURUKSHETRA UNIVERSITY,

KURUKSHETRA-136119

BCA III

BCA - 301 (Object Oriented Programming Using C++)

Writer: Er. Matish Garg Vetter: Prof. Rajender Nath

Lesson no. 09

Console I/O Operations and Type Conversions in C++


UNIT – IV
Structure:

9.1 Introduction

9.2 Objectives

9.3 Stream Classes

9.4 Unformatted I/O Operations

9.5 Formatted I/O Operations

9.5.1 ios class Functions and Flags

9.5.2 Manipulators

9.5.3 User-defined Manipulators

9.6 Type Conversions

1
9.6.1 Basic Type Conversion

9.6.2 Conversion from Basic Type to Class Type

9.6.3 Conversion from Class Type to Basic Type

9.6.4 Conversion from One Class Type to Another Class Type

9.7 Summary

9.8 Suggested Readings

9.9 Self Assessment Questions

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

discussed in this chapter.

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

type conversions are explained briefly in this chapter.

9.2 Objectives

After going through this lesson, you will be able to:

 Understand the concept of stream and stream classes in C++.

 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.

 Know how to define user-defined output functions.

 Describe type conversions between basic (built-in) data types.

 Describe type conversions between User-defined data types.

 Describe type conversions from basic data types to user-defined data types and vice-

versa.

9.3 Stream Classes

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

examples of predefined input and output streams in C++ respectively.

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

console unit is shown in the figure 9.1.

4
ios

istream streambuf ostream

iostream

istream_withassign iostream_withassign ostream_withassign

Figure 9.1 Stream classes for console I/O operations

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

interface to physical devices through buffers.

9.4 Unformatted I/O Operations

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:

I. >> (Extraction operator) and << (Insertion operator)

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:

cin >> Variable1 >> Variable2 >> ………..>> VariableN;

Variable1, Variable2, …….. are variable names that have been declared already in the

program.

The input data for this statement would be like this.

Data1 Data2 Data3 ………….. dataN

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;

cin >> 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

3442 to the Number.

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:

cout << Variable1 << Variable2 << ………..<< VariableN;

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:

cout<< “ Message1”<< “Message2”<<……… << “ MessageN”;

For example

cout<< “ The Number entered is ”<< Number;

The output is

The Number entered is 3442

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:

 get (char *): it assigns the input character to its argument.

 get (void): it returns the input character.

For example

char ch;

cin.get ( ch ); // get a character and assigns it to the argument ch

ch = cin.get( ); // returns the input value and assigns it to the variable ch

The put ( ) function (a member of ostream) is used to display a character and invoked by the

object cout.

For example

cout.put (ch ); // displays the value of variable ch

cout.put (‘a’); // displays the character a

Let us take a program to read and display a line of text using get ( ) and put ( ) functions.

#include < iostream.h >

# include < constream.h>

void main ( )

clrscr ( );

8
char ch ;

cout << “ input text \n”;

ch = cin.get ( );

while( ch != ‘\n’)

cout.put ( ch );

cin.get (ch );

INPUT

Good Morning India

OUTPUT

Good Morning India

III. getline ( ) and write ( ) Functions

The getline ( ) function is used to read a whole line of text that ends with a newline

character. It is also invoked by the object cin. The syntax is as follows:

cin. getline ( line, size );

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];

cin. getline ( Text, 15);

Suppose the input be

Good Morning India

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

cout. write ( line, size );

The first argument represents the name of string to be displayed and the second argument

indicates the no. of characters to display in the string.

For example:

cout. write (“ Morning”,5);

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

follow the string.

10
Let us take a program to read and display a string using getline ( ) and write ( ) functions.

#include < iostream.h >

# include < constream.h>

void main ( )

clrscr ( );

char ch [25] ;

cout << “ input any string \n”;

cin.getline (ch, 25);

cout << “ Entered string : ”;

cout.write( ch, strlen(ch));

INPUT

Good Morning India

OUTPUT

Entered string : Good Morning India

9.5 Formatted I/O Operations

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.

These functions are

i. ios class function and flags

ii. Manipulators

iii. User-defined output functions

9.5.1 ios class Function and Flags

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. All these functions are invoked by the object cout.

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.

fill ( ) Specify a character to fill the blank space of a field.

setf ( ) Specify various format flags that can control the form of output to be

displayed.

unsetf ( ) Remove the flags specified.

Table 9.1 ios class functions

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.

The object cout is used to invoke this function as follows:

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.

Let us take an example

#include < iostream.h >

# include < conio.h>

void main ( )

clrscr ( );

int x;

cout.width ( 6 );

cout<< “ RAM”;

cout.width ( 4 );

13
cout<< 23 << “\n”;

x = cout.width ( 1 );

cout<< “ Previous width setting = ”<< x;

OUTPUT

R A M 2 3

Previous width setting = 4

In the above program “RAM” and 23 are displayed as per the field setting and the value of x

shows the previous field setting i.e. 4.

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

then C++ automatically expands the field to fit the value.

II. precision( ) Function

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

following statement is used.

int x = cout. precision ( );

it returns the current precision value and assigns it to x.

Let us take an example.

#include < iostream.h >

# include < conio.h>

void main ( )

clrscr ( );

int x;

cout.precision ( 4 );

cout<< 5.44489 <<”\n”;

cout<< 23.005676 << “\n”;

x = cout.precision ( );

cout<< “ Current Precision Value = ”<< x;

15
OUTPUT

5.4448

23.0056

Current Precision Value = 4

III. fill ( ) Function

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

used with escape sequences.

Let us take an example

#include < iostream.h >

# include < conio.h>

void main ( )

clrscr ( );

char x;

16
cout.fill( ‘#’);

cout.width ( 6 );

cout<< “ RAM”<<”\n”;

x = cout.fill ( );

cout<< “ Padding character = ”<<x;

OUTPUT

# # # R A M

Padding character = #

IV. setf ( ) Function

The setf( ) function stands for set flags. This function is used in C++ for setting the flags to

format the output to be displayed. The syntax is as follows:

cout.setf ( arg1, arg2);

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

formatting flags, their formatting actions and their bit fields.

17
S. No. Formatting Bit Field(arg2) Formatting Output

Flag(arg1)

1 ios : : left ios : : adjustfield Left-justified output

2 ios : : right ios : : adjustfield Right-justified output

3 ios : : internal ios : : adjustfield Padding after sign

4 ios : : scientific ios : : floatfield Scientific notation

5 ios : : fixed ios : : floatfield Fixed point notation

6 ios : : dec ios : : basefield Decimal base

7 ios : : oct ios : : basefield Octal base

8 ios : : hex ios : : basefield Hexadecimal base

Table 9.2 flags and bit fields used in setf ( ) function

Let us consider following program using the setf ( ) function.

#include < iostream.h >

# include < conio.h>

void main ( )

clrscr ( );

cout.fill( ‘#’);

cout.setf(ios : : left, ios : : adjustfield);

cout.width ( 6 );

cout<< “ RAM”<<”\n”;

18
}

OUTPUT

R A M # # #

Here the output is left-justified and padded with #.

Some flags do not have bit fields and therefore they are used as single argument in setf ( )

function.

For example

cout.setf (ios : : showpoint);

display the value with trailing decimal point and trailing zeros when the data element is

printed. If default precision is used, the number 56 will be displayed as 56.000000.

The table 9.3 shows the list of flags and their actions that do not have bit fields.

S. No. Formatting Flag Formatting Output

1 ios : : showbase Use base indicator on output

2 ios : : showpos Print + before positive numbers

3 ios : : showpoint Show trailing decimal point and zeros

4 ios : : uppercase Use uppercase letters for hex output

5 ios : : skipus Skip white space on input

6 ios : : unitbuf Flush all streams after insertion

7 ios : : stdio Flush stdout and stderr after insertion

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:

cout. unsetf ( arg1);

where arg1 is the name of flag which is to be removed.

For example:

cout.unsetf (ios : : left);

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

functions and flags. The general syntax is as follows:

cout << manipulator1<< manipulator2<<….<< data1;

More than one manipulators can be used in a statement as shown above.

For example

cout << setw(5) << 56;

prints the data value 56 right-justified in a field width of 5 characters.

Table 9.4 shows some important manipulators with their actions.

20
S. No. Manipulators Description Equivalent ios

functions

1 setw ( int w) Set the field width to w. width( )

2 setprecision (int n) Set the floating point number precision( )

precision to n.

3 setfill ( int ch) Set the fill character to ch. fill ( )

4 setiosflags(long f) Set the format flag f. setf( )

5 resetiosflags(lonf f) Clear the flag specified by f. unsetf ( )

6 endl Insert new line and flush stream. “ \n ”

Table 9.4 Manipulators

9.5.3 User-defined Manipulators

Users can create their own manipulators for some special purposes. The general syntax for creating

a manipulator without any argument is as under:

ostream & < Manipulator-Name> ( ostream & output)

………………. // code

……………….

………………..

return output;

21
Here Manipulator _Name is the name of manipulator to be created.

Let us take a program to create a manipulator ‘ line’ equivalent to “\n”.

#include < iostream.h >

# include < conio.h >

#include < iomanip.h>

ostream & line ( ostream & output)

output << “\n”;

return output;

void main ( )

clrscr ( );

cout<< “ RAM”<<line<< “SHAM”;

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 >

# include < conio.h >

#include < iomanip.h>

ostream & tab ( ostream & output)

output << “\t”;

return output;

void main ( )

clrscr ( );

cout<< “ RAM”<<tab<< “SHAM”;

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.

9.6 Type Conversions

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.

i. Basic Type Conversion

ii. Conversion from Basic Type to Class Type

iii. Conversion from Class Type to Basic Type

iv. Conversion from One Class Type to Another Class Type

9.6.1 Basic Type Conversion

C++ allows implicit as well as explicit type conversions when various basic built-in data types are

mixed in the expression.

a) Implicit Type Conversion: Implicit type conversion (also called Automatic Type

Conversion) is performed by the compiler automatically whenever one fundamental data

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

result. For Example

long x = 45; // integer is widened into long

Here integer 45 is promoted to long data type.

When we convert a value from a larger type to a smaller type, or between different types,

this is called a numeric conversion. For example

double d = 6; // integer is converted into double

short s = 8; // integer is converted into short

Conversions may or may not result in a loss of data. Because of this, any code that does an

implicit conversion will often cause the compiler to issue a warning.

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

described in the table 9.5 as given below:

25
Operand 1 Operand 2 Resulting Data type

char int int

char float float

char double double

int float float

int double double

int long long

float double double

long float float

long double double

Table 9.5 Implicit Type Conversions

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

conversion. Consider this case:

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 ( )

operator. The following are the syntaxes of typecasting in C and C++.

(data- type name) expression // C style syntax

data-type name (expression) // C++ style syntax

Let us reconsider the above example by using typecast operator:

float f = float (x) / y; // C++ style syntax

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.

9.6.2 Conversion from Basic Type to Class Type

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

variable into a class type object.

#include < iostream.h >

# include < conio.h >

class Time

27
int hours;

int minutes;

public:

Time( int t )

hours = t/60;

minutes = t % 60;

void show ( )

cout << hours<< “ hours ”<<minutes << “ minutes \n”;

};

void main ( )

Time T1, T2;

int period1 = 95;

int period2 = 75;

T1 = Time(period1);

T2 = period2;

T1.show ( );

T2.show ( );

28
OUTPUT

1 hours 35 minutes

1 hours 15 minutes

Here the statement

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;

perform the same thing by invoking the constructor implicitly.

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

accomplished by using an overloaded = operator.

9.6.3 Conversion from Class Type to Basic Type

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:

 It must be a class member function.

 It must not have any argument.

 It must not have a return type.

The general form of an overloaded casting operator function is as under:

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.

vector : : operator double ( )

double sum = 0 ;

for ( int i = 0; i<size; i++)

sum = sum + v[i] * v[i];

return sqrt ( sum );

Since it a member function, it is invoked by the object as follows:

double length = double (V1);

or

double length = V1;

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:

#include < iostream.h >

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;

a = D; // operator int ( ) is executed

b = D; // operator float ( ) is executed

cout<< “ \n value of a : ” << a;

cout<< “ \n value of b: ” << 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.

9.6.4 Conversion from One Class Type to Another Class Type

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:

objA = objB; // objects of class A and class B

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,

either it is by type conversion function (casting operator function) or by using a constructor.

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

shown in figure 9.2.

objA = objB // A is destination class & B is source class

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.

objA = objB // A is destination class & B is source class

Class A(destination) Class B (Source)

Constructor Data access


function Argument of type B functions

Conversion takes place here

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

using a constructor function.

#include <iostream.h>

#include <stdlib.h>

#include <string.h>

#include <conio.h>

class Date // destination class

char dt[12];

public:

Date( )

dt[0] = NULL;

void display( )

cout<< dt;

Date (DMY p) // one argument constructor

int dy = p.day ( );

int mth = p.month ( );

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);

};

class DMY // source class

int dy, mth, yr;

public:

DMY( int d, int m, int y)

dy = d;

mth = m;

yr = y;

int day ( )

return ( dy );

35
}

int month ( )

return ( mth );

int year ( )

return ( yr );

void display ( )

cout << dy << “ ” << mth<< “ ”<<yr;

};

void main ( )

clrscr( );

DMY D1( 1,1,2016);

Date D2;

D2 = D1;

cout << “\n 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

convert DMY type to Date type.

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)

Unformatted I/O functions.

 >> (Extraction operator), << (Insertion operator), get ( ), put ( ), getline ( ) and write ( )

are some unformatted I/O functions.

 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.

 Manipulators are pre-defined in the header file ‘iomanip.h’.

 They provide the same features as that of the ios functions and flags.

 User-defined manipulators can be created for some special purposes.

 Type conversion is the process of converting the value of variables in an expression

from one type to another type.

 C++ allows implicit as well as explicit type conversions.

 Implicit type conversion (also called Automatic Type Conversion) is performed by the

compiler automatically whenever one fundamental data type is expected, but a different

fundamental data type is supplied.

 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

conversion function (casting operator function) or by using a constructor.

 The casting operator function is located in the source class.

 One argument constructor function must be defined in the destination class.

9.8 Suggested Readings

 Object Oriented Programming With C++ By E Balagurusamy, TMH.

 Object Oriented Programming With Ansi & Turbo C++ By Ashok N. Kamthane, Pearson

Education.

 The Complete Reference C++ By Herbert Schildt, TMH

 The C++ Programming Language By Bjarne Stroustrup, Pearson Education.

 Object Oriented Programming in C++ By Roberrt Lafore, SAMS Publishing.

9.9 Self Assessment Questions

1. Define stream and stream classes.

2. How does I/O system in C++ differ from that in C?

3. What are formatted and unformatted I/O functions?

4. What is the significance of header file iostream.h in C++? Discuss.

5. What is the role of header file iomanip.h in C++?

39
6. What is the role of extraction operator and insertion operator in I/O system? Discuss

with examples.

7. Describe the use of getline ( ) function with an example.

8. What is the difference between get ( ) and getline ( ) functions? Explain with an

example.

9. What is the difference between put ( ) and write ( ) functions?

10. Explain the procedure for creating user-defined manipulators.

11. List the formatting flags that do not have bit fields.

12. What is the use of precision ( ) function in C++? Give an example.

13. What do mean by typecasting? Explain the difference between implicit and explicit

typecasting.

14. What is the difference between typecasting in C and C++?

15. Define casting operator or conversion function. Explain its syntax. What are the

necessary conditions for it?

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

class and display them in tabular form.

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

hexadecimal number by using setf ( ) function.

24. Write a program to convert the hexadecimal number into its equivalent decimal number

by using setf ( ) function.

25. Write a program to convert a number into its equivalent scientific notation using

formatted I/O function.

26. Write a program to enter some text upto 200 characters. Ignore vowels and replace them

with # using fill ( ) function.

27. What is the output of the following code?

void main ( )

cout.fill ( ^ );

cout.precision ( 3 );

cout.setf ( ios : : left , ios : : adjustfield );

cout.setf ( ios : : scientific , ios : : floatfield );

cout.width ( 15 );

cout << 899.675434;

28. Write a program to create a single user-defined manipulator which provides following

format specifications to output result.

a) 15 coulmn width

b) Left justified

41
c) Four digits precision

d) Filling of blank spaces with $

e) Show + before positive numbers

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

casting operator function.

32. Write a program to declare two classes minutes and hours. Convert minutes to hours by

using user-defined conversion routines.

33. Write a program to convert integers or floats to complex type data by using both casting

operator function as well as constructor.

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.

Genericity in C++: Templates in C++, Function templates, Class templates in C++.


Exception Handling in C++: try, throw and catch;

Introduction to files handling in C++


DIRECTORATE OF DISTANCE EDUCATION

KURUKSHETRA UNIVERSITY,

KURUKSHETRA-136119

BCA III

BCA - 301 (Object Oriented Programming Using C++)

Writer: Er. Matish Garg Vetter: Prof. Rajender Nath

Lesson no. 10

File Handling in C++


UNIT – IV
Structure:

10.1 Introduction

10.2 Objectives

10.3 File Stream Classes

10.4 Opening and Closing a File

10.5 Detecting End-of-file

10.6 File Opening Modes

10.7 File Pointers and Their Manipulations

10.8 Sequential I/O Operations

10.9 Random Access: Updating A File

1
10.10 Error Handling Functions

10.11 Command Line Arguments

10.12 Summary

10.13 Suggested Readings

10.14 Self Assessment Questions

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

After going through this lesson, you will be able to:

 Understand the concept of stream and classes for file streams in C++.

 Know how to open and close a file.

 Describe different file opening modes.

 Describe file pointers and their manipulations.

 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

stream writes data to the file.

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.

Class Details and purpose

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.

Table 10.1 Details of file stream classes

4
ios

iostream file

istream streambuf ostream

iostream

------------------------------------------------------------------------------------------------------------------------

ifstream fstream ofstream

fstream file
filebuf
fstream base

Figure 10.1 File Stream classes for file I/O operations

10.4 Opening and Closing a File

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.

A file is opened in two ways:

I. By using the constructor function of the class.

II. By using the member function open ( ) of the class.

The first method is used for a single file in the stream but the second method is used for managing

multiple files in the stream. Both methods are explained as under:

 Opening file using constructor function: It comprises two steps:

i. Create a file stream object using the suitable class i.e. ofstream class is used for

output stream and ifstream is used for input stream.

ii. Initialize the file stream object with the file name.

The constructor uses the file name as argument and opens the file.

Consider the following statements

ofstream fout(“student”); // for output

ifstream fin(“test”); // for input

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:

fout << name; // write contents of variable name in student file

fout << age; // write contents of variable age in student file

fout << “ Ram”; // write Ram in student file

fin >> marks; // read contents of variable marks from test file

fin >> subject; // read contents of variable subject from test file

Let us consider the following programs:

#include <iostream.h>

#include <fstream.h>

#include <conio.h>

void main ( )

ofstream fout ( “student”);

out << “ Name Age \n”;

out << “ Ram 15 \n”;

out << “ Jhon 16 \n”;

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

contents are deleted. The file is presented as a clean file.

#include <iostream.h>

7
#include <fstream.h>

#include <conio.h>

void main ( )

# define N 30;

char line[N];

ifstream fin ( “student”);

while(fin)

fin . getline (line, N);

cout << line << “\n”;

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

of file is reached, the while loop is terminated.

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.

Let us take an example:

#include <iostream.h>

#include <fstream.h>

#include <conio.h>

int main ( )

ofstream fout ( “student”);

cout << “Enter student name: ”;

char name[30];

cin >> name;

fout << name << “\n”; // write name to the file

cout << “ Enter Roll No: ”;

int Rollno;

cin >> Rollno;

fout << Rollno << “\n”; // write Rollno to the file

fout.close( ); // closes the file associated with fout

9
ifstream fin ( “student”);

fin >> name; // read name from file

fin >> Rollno; // read Rollno from file

cout << “ Student name : ” << name << “\n”;

cout << “ Roll No : ” << Rollno <<”\n”;

fin.close ( ); // closes the file associated with fin

return 0;

OUTPUT

Enter student name: Ram

Enter Roll No: 56

Student name : Ram

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

displayed on the screen.

 Opening file using the member function open ( )

The function open ( ) is used to open multiple files sequentially by using the same stream

object. The general syntax of the function is:

File-stream-class Stream-object;

10
Stream-object . Open (“filename”);

For example:

ofstream fout;

fout. open (“ student”);

------------------

------------------

fout.close( );

fout. open (“ marks”);

-----------------

-----------------

fout.close( );

Here two files are opened in sequence for writing the data by the same file object.

Let us consider a program using the function open ( ).

#include <iostream.h>

#include <fstream.h>

#include <conio.h>

int main ( )

ofstream fout; // create output stream

fout. open(“ fruit”); //open file fruit

fout << “ apple\n”;

fout << “ orange\n”;

fout << “ banana\n”;

11
fout.close ( ); // close fruit

fout.open(“ vegetable”); // open file vegetable

fout << “potato\n”;

fout << “ tomato\n”;

fout << “ cabbage\n”;

fout.close ( ); // close vegetable

const int N = 50; // size of line

ifsream fin; // create input stream

fin.open (“ fruit”); // open fruit

cout << “ names of fruit : \n”;

while (fin)

fin.getline(line, N); // read a line

cout << line;

fin.close ( ); // close fruit

fin.open (“ vegetable”); // open vegetable

cout << “ names of vegetable : \n”;

while (fin)

fin.getline(line, N); // read a line

cout << line;

12
fin.close ( ); // close vegetable

return 0;

OUTPUT

names of fruit :

apple

orange

banana

names of vegetable :

potato

tomato

cabbage

10.5 Detecting End-of-file

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

a non-zero value if end of file is encountered otherwise zero.

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.

Consider the following program.

#include <iostream.h>

#include <fstream.h>

#include <conio.h>

int main ( )

const int N = 50; // size of line

ifsream fin; // create input stream

fin.open (“ fruit”); // open fruit

cout << “ names of fruit : \n”;

while (fin.eof ( ) = = 0)

fin.getline(line, N); // read a line

cout << line;

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.

10.6 File Opening Modes

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 ( )

with two arguments is

Stream-object.open (“ filename ”, mode);

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.

Table 10.2 File opening modes


15
When the function open ( ) uses only one argument, it uses default values for the second parameter

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

it in ios :: trunk mode by default.

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

the data anywhere in the file.

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

fstream class does not provide the mode by default.

vi. The file can be opened by combining two or more mode parameters using the bitwise or

operator( | ) as shown in the example given below:

fout. open( “ fruit ”, ios :: app | ios :: nocreate )

it opens the file in the append mode but fails to open if the file does not exist.

Consider the following program.

#include <iostream.h>

#include <fstream.h>

#include <conio.h>

int main ( )

16
{

ofstream fout; // create output stream

fout. open(“ fruit”, ios ::out); //open file fruit for writing only

fout << “ apple\n”;

fout << “ orange\n”;

fout << “ banana\n”;

fout.close ( ); // close fruit

fout. open(“ fruit”, ios ::app); //open fruit again in append mode

fout << “ grapes\n”;

fout.close ( ); // close fruit

fout.open(“vegetable”, ios :: out); // open vegetable for writing only

fout << “potato\n”;

fout << “ tomato\n”;

fout << “ cabbage\n”;

fout.close ( ); // close vegetable

fout.open(“vegetable”, ios :: app); //open vegetable in append mode

fout << “carrot\n”;

fout.close ( ); // close vegetable

const int N = 50; // size of line

ifsream fin; // create input stream

fin.open (“ fruit”, ios :: in); // open fruit for reading only

cout << “ names of fruit : \n”;

while (fin.eof ( ) = = 0)

17
{

fin.getline(line, N); // read a line

cout << line;

fin.close ( ); // close fruit

fin.open (“ vegetable”); // open vegetable for reading only

cout << “ names of vegetable : \n”;

while (fin.eof ( ) = = 0)

fin.getline(line, N); // read a line

cout << line;

fin.close ( ); // close vegetable

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

then opened for reading purpose by using ios :: in mode.

10.7 File Pointers and Their Manipulations

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

a specified location in the file.

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.

Table 10.3 Functions for Manipulation of File Pointers

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

numbered beginning from zero.

Similary, the statements

fout.open( “ fruit ”, ios :: app);

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:

seekg ( offset, position ) ;

seekp ( offset, position );

where offset represents the number of bytes the file pointer is to be moved from the location

specified by the position parameter. The value of position parameter may be

 ios :: beg beginning of the file


 ios :: cur current position of the pointer
 ios :: end end of the file
Table 10.4 describes some output pointer offsets associated with seekp ( ) function.

Seek calls Meaning


fout.seekp( 0, ios :: beg ) Go to the beginning of the file.
fout.seekp( 0, ios :: cur ) Keep on the current position.
fout.seekp( 0, ios :: end ) Go to the end of the file.
fout.seekp( n, ios :: beg ) Moves to (n+1) th byte of the file.
fout.seekp( n, ios :: cur ) Moves n bytes forward to the current position.
fout.seekp( -n, ios :: cur ) Moves n bytes backward to the current position.
fout.seekp( -n, ios :: end ) Moves n bytes backward from the end.
Table 10.4 seekp functions with arguments

20
The following program writes data in the file. Read the data from the end of the file and then

display it in reverse order.

#include <iostream.h>

#include <fstream.h>

#include <conio.h>

int main ( )

ofstream fout; // create output stream

char name[30];

fout. open(“ Data ”, ios :: out); //open file Data

cout << “ enter name\n”;

cin >> name;

fout << name;

fout.close ( ); // close file

ifsream fin; // create input stream

fin.open (“Data ”, ios :: in); // open Data file

cout << “ name in reverse order : \n”;

fin. seekg( 0, ios ::end ); // moves the pointer to end of the file.

int n = fin. tellg( ); // gives number of bytes

char ch;

for( int i = 1; i<= n; i++)

21
fin. seekg( -i, ios :: end); // moves backward by i bytes

fin >>ch;

cout << ch;

return 0;

OUTPUT

enter name

darshan

name in reverse order :

nahsrad

10.8 Sequential I/O Operations

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 ( ) and put ( ) functions

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 ( )

fstream F; // create input and output stream

char text[30];

cout << “ Enter data\n”;

int len = strlen ( text );

F. open(“ Data ”, ios :: in | ios :: out); //open file Data

for( int i = 1; i<=len; i++)

F.put ( text [i] ); // write a character to the file

F.seekg ( 0 );

char ch;

While (F.eof ( ) = = 0)

F.get ( ch ); // read a character from the file

cout << ch;

return 0;

23
OUTPUT

Enter data

Good Morning

Good Morning

 read ( ) and write ( ) functions

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

the data which makes the saving much faster.

The general syntax of read ( ) and write ( ) functions are as under:

Input stream-object. read ( (char *) & var, sizeof (var));

Output stream-object. write ( (char *) & var, sizeof (var));

These functions take two arguments. The first is the address of variable var and the second

is the length of variable var in bytes.

Let us consider an example showing the use of these functions.

#include <iostream.h>

#include <fstream.h>

#include <string.h>

int main ( )

24
int number[ ] = { 10, 20, 30, 40, 50, 60 };

ofstream fout;

fout. open(“ Numeric ”); //open file Numeric

fout. write ( ( char *) & number, sizeof ( number ));

fout.close ( ); // close file

for( int i = 0; i<6; i++)

number[i] = 0; // clears data from memory

ifstream fin;

fin. open ( “ Numeric” ); // open file Numeric

fin. read (( char *) & number, sizeof ( number ));

for( int i = 0; i<6; i++)

cout << number[i] ,, “\t”;

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

displayed on the screen.

 Reading and writing a class object

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

functions are not. Consider the following example:

#include<iostream.h>

#include<fstream.h>

#include<iomanip.h>

class Vehicle

char Name[30];

float price;

public:

void getdata ( );

void display ( );

};

void Vehicle : : getdata ( )

cout<< “ Enter the name:”;

cin>>Name;

cout<< “ Enter Price:”;

cin>>price;

void Vehicle : : display ( )

26
{

cout<< “ Name:” << Name << “\n”;;

cout<< “ Price:” << price << “\n”;

void main ( )

Vehicle Two_wheeler [3];

fstream file;

file.open(“vehicles.dat”, ios :: in | ios :: out);

cout<< “ Enter details of three vehicles in the file\n”;

for ( int i=0 ; i<3; i++ )

Two_wheeler [i].getdata ( );

file.write((char*) & Two_wheeler[i], sizeof(Two_wheeler[i]);

file.seekg(0);

cout << “ Details of vehicles are\n”;

for ( int i=0 ; i<3; i++ )

file.read((char*) & Two_wheeler[i], sizeof(Two_wheeler[i]);

Two_wheeler [i].display ( );

27
INPUT

Enter details of three vehicles in the file

Enter the name: Cycle

Enter Price: 2500

Enter the name: Scooter

Enter Price: 35000

Enter the name: Motor Cycle

Enter Price: 45000

OUTPUT

Details of vehicles are

Name: Cycle

Price: 2500

Name: Scooter

Price: 35000

Name: Motor Cycle

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

Updating a file includes one of the following tasks:

 Displaying the contents of a file.

 Modifying an existing data item.

 Adding new data item.

 Deleting an existing data item.

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:

int location = n * object_length;

where length of the object is achieved by using sizeof operator as follows:

int object _length = sizeof ( object );

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

data item in it.

#include<iostream.h>

#include<fstream.h>

#include<iomanip.h>

class Vehicle

29
{

char Name[30];

float price;

public:

void getdata ( );

void display ( );

};

void Vehicle : : getdata ( )

cout<< “ Enter the name:”;

cin>>Name;

cout<< “ Enter Price:”;

cin>>price;

void Vehicle : : display ( )

cout<< “ Name:” << Name << “\n”;;

cout<< “ Price:” << price << “\n”;

void main ( )

Vehicle Two_wheeler;

fstream file;

30
file.open(“vehicles.dat”, ios :: ate | ios :: in | ios :: out | ios :: binary);

file.seekg( 0, ios :: beg);

cout<< “ current data of the file\n”;

while (file.read((char*) & Two_wheeler, sizeof(Two_wheeler)))

Two_wheeler.display ( );

file. clear ( ); // reset the value of EOF flag

cout << “ Add another vehicle\n”;

Two_wheeler.getdata ( );

char ch;

cin.get(ch);

file.write((char*) & Two_wheeler, sizeof(Two_wheeler);

file.seekg(0);

cout << “ Data of the appended file\n”;

while (file.read((char*) & Two_wheeler, sizeof(Two_wheeler)))

Two_wheeler.display ( );

OUTPUT

current data of the file

31
Name: Cycle

Price: 2500

Name: Scooter

Price: 35000

Name: Motor Cycle

Price: 45000

Add another vehicle

Enter the name: TVS Scooty

Enter Price: 37000

Data of the appended file

Name: Cycle

Price: 2500

Name: Scooter

Price: 35000

Name: Motor Cycle

Price: 45000

Name: TVS Scooty

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.

 Invalid file name.

 The file name used for a new file may already exist.

 An attempt to read a file which does not exists.

 Insufficient disk space.

 An invalid operation such as reading data past the end of file.

 Writing data to the file which is opened in read only mode.

 Opening a file which is already opened by another program.

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).

Table 10.5 Error Handling Functions

33
The above functions may be used in the appropriate places in the program to find the status of the

file stream and to take corrective actions. For example:

ifstream fin;

fin. open (“XYZ”);

while (fin. fail ( ))

…………. //process the file

………….

if ( fin . eof ( ) )

…………. // terminate program normally

………….

else if(fin . bad ( ) )

…………. // reort error

………….

else

fin .clear( );

…………..

34
}

The function clear ( ) resets the error states (flags) so that further operations can be performed.

10.11 Command Line Arguments

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

the program to be executed. For example:

C > result student subject

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

main( int argc, char * argv[ ] )

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

C > result student subject

Value of argc is 3 and argv would be an array of three pointers to strings as shown below:

argv[0] --> result

argv[1] --> student

argv[2] --> subject

35
Now argv[1] and argv[2] can be used as the file names in the file handling operations such as

fin. open( argv[1] ); // open data file for reading

fout.open( argv[2] ); // open data file for writing

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.

It is nothing just a sequence of bytes.

 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

member function open ( ) of the class.

 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

encountered otherwise zero.

 Different file opening modes are used to open the file depending upon the operation to be

carried out with the file.

 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 a specified location in the file.

 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 put pointer.

 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

the main ( ) function.

10.13 Suggested Readings

 Object Oriented Programming With C++ By E Balagurusamy, TMH.

 Object Oriented Programming With Ansi & Turbo C++ By Ashok N. Kamthane, Pearson

Education.

 The Complete Reference C++ By Herbert Schildt, TMH

 The C++ Programming Language By Bjarne Stroustrup, Pearson Education.

 Object Oriented Programming in C++ By Roberrt Lafore, SAMS Publishing.

37
10.14 Self Assessment Questions

1. Define input streams and output streams.

2. Describe various classes available for file operations.

3. What is a file? Describe the methods of opening a file with examples.

4. Explain the syntax ad meaning of eof ( ) function.

5. What are the different types of file opening modes? Explain with examples.

6. Describe different file manipulators.

7. What are the advantages of saving the data in binary form?

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

handling functions with examples.

11. What are command line arguments?

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.

14. Write a program to copy contents of a file to another file.

15. Write a program to exchange contents of two files.

16. Write a program to compare two files in terms of their size.

17. Write a program to count characters and numericals present in a file.

18. Write a program to check whether a file is successfully opened or not.

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.

23. Write a program to find the length of a file.

39

You might also like