133805901735423145

Download as pdf or txt
Download as pdf or txt
You are on page 1of 227

Self Learning Material

OOPS Using C++


(BSBC-203)

Course: Bachelors of Computer Applications


Semester-II

Distance Education Programme


I.K. Gujral Punjab Technical University
Jalandhar
Syllabus
I.K. Gujral Punjab Technical University

BSBC203 OOPS USING C++

Objective & Expected Outcome: The objective of this course to learn programming from real
world examples and understanding object oriented approach for finding solutions to various
problems with the help of C++ language. Students will learn to create computer based
solutions to various real-world problems using C++ and will learn various concepts of object
oriented approach towards problem solving.
SECTION-A
Introduction: Object oriented programming approach, characteristics of object orientated
languages, Bridging C & C++ (Overview of C Concepts).
Structures and Unions: Declaration of structures, Accessing structure members, Structure
Initialization, Arrays of structure, nested structures, structure with pointers, functions &
structures, Unions, Structure/Union Versus Class in C++.
Class Declaration: Data Members, Member Functions, Private and Public Members, Data
Hiding and Encapsulation, Array within a class. (12)
SECTION-B
Class Function Definition: Member Function definition inside the class and outside the class,
Friend Function, Inline Function, Static Members & Functions, Scope Resolution Operator,
Private and Public Member Functions, Nesting of Member Functions.
Creating Objects, Accessing class data members, Accessing member functions, Arrays of
Objects, Objects as function arguments: Pass by value, Pass by reference, Pointers to Objects.
Constructors and Destructors: Declaration and Definition, Default Constructors, Parameterized
Constructors, Constructor Overloading, Copy Constructors. Destructors: Definition and use.
(12)
SECTION-C
Inheritance - Extending Classes Concept of inheritance, Base class, Derived class, Defining
derived classes, Visibility modes : Private, public, protected; Single inheritance :
Privately derived, Publicly derived; Making a protected member inheritable, Access Control to
private and protected members by member functions of a derived class, Multilevel inheritance,
Nesting of classes.
Function Overloading & Operator Overloading: Binary & Unary. (12)
SECTION-D
Polymorphism: Definition, early Binding, Polymorphism with pointers, Virtual
Functions, late binding, pure virtual functions.
Input/output files: Streams, buffers & iostreams, header files, redirection, file input and
output. (12)

Suggested Readings / Books:


1. Object Oriented Programming with C++, E. Balagurusami, Fourth Edition, Tata Mc-Graw
Hill
2. Object Oriented Programming in Turbo C++, Robert Lafore, Fourth Edition Galgotia
Publications.
3. The C++ Programming Language, Bjarna Stroustrup, Third Edition, Addison-Wesley
Publishing Company.
4. Object Oriented Programming Using C++, Salaria, R. S, Fourth Edition, Khanna Book
Publishing
Table of Contents
Chapter No. Title Page No.
1 Overview of Structured and OOP Languages. 1
2 Fundamentals of structure 13
3 Advanced concepts- Structure 24
4 Fundamentals of class 38
5 Definition of member functions 48
6 Class Objects 61
7 Constructors and destructors 77
8 Friend function and friend class 94
9 Static members 111
10 Fundamentals of inheritance 126
11 Implementing Inheritance 140
12 Polymorphism and function overloading 160
13 Operator Overloading 173
14 Virtual functions 190
15 I/O Streams 203
16 File Handling 213

Written by:
Seema Gupta, Assistant Professor,
Mayur College, Kapurthala
Reviewed by:
Dr.Vinay Chopra,
Asssitant Professor, DAVIET, Jalandhar

© IK Gujral Punjab Technical University Jalandhar


All rights reserved with IK Gujral Punjab Technical University Jalandhar
Lesson- 1 Overview of Structured and OOP Languages.
Structure
1.0 Objective
1.1 Introduction
1.2 Need for Software Engineering
1.3 Evolution of Programming Languages
1.4 Features of Object Oriented Programming
1.5 Difference between Structured Programming and Object Oriented Programming
1.6 Bridging C and C++
1.6.1 Keywords
1.6.2 Operators
1.6.3 Data types in C++
1.6.4 Input/ Output using C++
1.6.5 Difference between C and C++ programming languages
1.7 Summary
1.8 Glossary
1.9 Answers to check your progress/self assessment questions
1.10 References/ Suggested Readings
1.11 Model questions

1.0 Objective
After studying this lesson, students will be able to:
1. Discuss the evolution and need of object oriented languages.
2. Define various features of object oriented programming.
3. Differentiate between structural and object oriented languages.
4. Explain the basic input and output operation using C++.
5. Differentiate between C and C++ programming languages.

1.2 Need for Software Engineering


Initially there was only the concept of hardware engineering and not software engineering. As the
generations passed by, the cost of software development grew exponentially and there was a software
crisis. Many of the software projects did start but failed to complete. The ones that were completed
and delivered were not used or contained too many errors. It happened because there was no software
engineering and most of the early efforts were focused on hardware engineering.

The early software paradigms failed to keep the pace with the change in user requirement that keeps
on changing at rapid pace. The early programming languages lacked the flexibility to incorporate

Page 1 of 223
changes or re-use the existing code. After a series of deliberations most of the researchers came to a
conclusion that your programming language must support the following features in order to survive:

1. Maintainability.
2. Reusability.
3. Openness.
4. Portability.
5. Security.

1.3 Evolution of Programming Languages


The software evolution over decades is viewed as layered growth. Layers of improvement were put on
the existing programming languages in order to show improvement. Initially the programming
languages had no phases. The programmers used to write the absolute machine code that was directly
understood by the computer. Only a few programmers were available and it was very difficult to
change the code. Next came the Assembly languages and Low level programming languages. With
assembly programming languages, the program was compiled in two phases. Assembly code was
converted into machine code and then executed. But nothing changed. The complexities still remained
the same.
The next big thing in computer programming evolution was the advent of middle level languages
using procedural and structural model. C programming language is the most popular structural
language. Still the structural programming failed to address the key issues like maintainability and
reusability. Then came the object oriented programming languages. Object oriented programming is
an extension of structural programming. Like C++ is an extension of C with powerful features that
makes it the most popular object oriented programming of all, used to develop some serious system
software.

Figure 1.1: Layered evolution of programming languages.

Page 2 of 223
1.4 Features of Object Oriented Programming
Following are some of the key features of object oriented programming:
1. Class- C++ which is an object oriented programming language was initially called C with classes.
A class is a user defined data type introduced in object oriented programming and it forms the basis
for any OOP language. A class may be defined as a collection or binding of data members and
member functions. All other objectives of object oriented programming can be achieved only with the
help of class data type and you cannot call any program or language supporting OOP paradigm if it
does not include class data type.
2. Object- A class is simply a data type that form the basis for OOP. Just like variable of any built-in
data type, you also need to create object of a class in order to use its features. An object may be
defined as instance of a class. It is only when you create objects of a class, memory instance is
allocated to the data members and member functions of that class. When you create multiple objects
of a class; multiple instances of data members are created, one for each object respectively.
3. Encapsulation- There was a clear separation between the data and functions in procedural or
structural languages. More emphasis was given to the coding than data. A class supports the
encapsulation feature of OOP. Encapsulation means binding of data and functions (coding) in a single
type. A class is a collection of data members and member functions, and hence it supports
encapsulation. Encapsulations leads to data hiding.
4. Data hiding- There were no means in structural programming to restrict the access of data. All data
could be accessed from outside the function or any structure. OOP programming came with the
concept of data hiding. You could create data members of a class using private access specifier that
cannot be accessed directly from outside the definition of the class. Member functions of the class are
normally defined using public access specifier and the private data member can be accesses through
them. It is an important feature of OOP because it helps you keep your data safe.
5. Abstraction- Abstraction in OOP means providing only the interface to the users and hiding the un-
necessary details or coding from the user. Abstraction is also a process of creating some abstract
object from a class that depicts a real life entity. Some of the examples of abstract objects are
employee, student, car, account, human, etc. The main objective of abstraction is to reduce the
complexity and improve the performance. A class that contains only the prototype of data members
and member functions is a perfect example of abstract view of class. You can access member function
of class using objects of that class without knowing any details about that member function.
6. Inheritance- It is probably the most powerful feature of object oriented programming. It lets you
create a new class by re-using or inheriting the features of already existing class and adding new
features to the same. Inheritance helps you to improve the reusability of your code by re-using already
tested classes. It helps to reduce a lot of programming effort and also improves the performance.
Inheritance also helps you to break one large class into smaller classes that helps improve the

Page 3 of 223
abstraction. Depending on the relationship between the classes, you can implement 5 types of
inheritances in C++.
7. Polymorphism- In yet another key feature of OOP, you can create multiple forms of a single entity.
That entity can be a function or an operator. Polymorphism is also known as overloading. You can
achieve function overloading or function polymorphism by creating multiple function definitions with
the same name that are different in respect to number of arguments or type of arguments. In C++
programming language, you can also redefine the already defined operators and make them work on
class objects like they work on variables of any data type.
8. Dynamic Binding- Dynamic binding is also a type of polymorphism. Dynamic binding can be
achieved in C++ using the concept of virtual function. Normally the binding of function definitions
with the respective function call statements is done statically at the compile time. But C++ lets this
binding to be delayed to the run time. It is at the run time when it is decided which function will be
called for execution. Dynamic binding can be implemented with the help of pointers and is applicable
only in case of inheritance. You will learn the concept of dynamic binding using virtual functions later
in SLM.

Check your progress/ Self assessment questions- 1

Q1. List various features that the researchers thought every programming language should support
after the software crisis phase.

Q2. List various programming languages according to the evolution of programming languages.

Q3. Explain the feature of inheritance in OOP.

Page 4 of 223
Q4. Dynamic binding can be achieved in C++ using the concept of .
1.5 Difference between structured programming and object oriented programming

Structured Programming Object Oriented Programming

Structured Programming focuses more on code/ logical


OOP focuses more on data.
structure and less on data.

Structured programming follows top-down approach of OOP follows bottom-up approach of


programming. programming.

Structured Programming is also known as Modular OOP supports inheritance, encapsulation,


Programming, a subset of procedural programming. abstraction, polymorphism, etc.

In Structured Programming, code is written into small


In OOP, functions are contained in classes.
self contained functions.

OOP is more secure and supports data


Structured Programming does not support data hiding.
hiding feature.

Structured Programming can solve moderately complex OOP can solve programs with high level
programs. of complexity.

Structured Programming provides slight reusability. OOP provides high degree of reusability,

Structured programming provides less support for OOP provides support for greater
abstraction and flexibility. abstraction and flexibility.

1.6 Bridging C and C++


1.6.1 Keywords
Keywords are the reserved words in any programming that have pre-defined meaning and cannot be
used as identifiers. In addition to keywords used in C programming language, following keywords
were added to C++ programming language. Depending on the compiler used, you may find that some
of them may not be supported by certain compilers.
Asm dynamic_cast namespace reinterpret_cast try
Bool Explicit new static_cast typeid
Catch False operator template typename
Class Friend private this using
const_cast Inline public throw virtual
Delete Mutable protected true wchar_t

1.6.2 Operators

Page 5 of 223
Following is the list of operators used in C++ programming according to the precedence. The
operators with higher precedence are evaluated first as compared to other operators. Associativity is
also listed for each operator. In case two operators have same precedence, they are evaluated in the
order of their associativity.

Precedence Operator Description Associativity

1 :: Scope resolution Left-to-right

++ -- Suffix/postfix increment and decrement

() Function call

2 [] Array subscripting

. Element selection by reference

-> Element selection through pointer

++ -- Prefix increment and decrement Right-to-left

+ − Unary plus and minus

! ~ Logical NOT and bitwise NOT

(type) Type cast

3 * Indirection (dereference)

& Address-of

sizeof Size-of

new, new[] Dynamic memory allocation

delete, delete[] Dynamic memory de-allocation

4 .* ->* Pointer to member Left-to-right

5 * / % Multiplication, division, and remainder

6 + − Addition and subtraction

7 << >> Bitwise left shift and right shift

< <= For relational operators < and ≤ respectively


8
> >= For relational operators > and ≥ respectively

9 == != For relational = and ≠ respectively

10 & Bitwise AND

11 ^ Bitwise XOR (exclusive or)

Page 6 of 223
12 | Bitwise OR (inclusive or)

13 && Logical AND

14 || Logical OR

?: Ternary conditional Right-to-left

= Direct assignment (provided by default for C++ classes)

+= −= Assignment by sum and difference


15
*= /= %= Assignment by product, quotient, and remainder

<<= >>= Assignment by bitwise left shift and right shift

&= ^= |= Assignment by bitwise AND, XOR, and OR

16 throw Throw operator (for exceptions)

17 , Comma Left-to-right

1.6.3 Data types in C++

Figure 1.2 Data types in C++


Most of the data types in C++ are inherited from C programming languages. A new user defined data
type "class" is introduced which is the back bone of C++. All concepts of OOP's can only be realized
using a class. It is a user defined data type. It is a collection of data members and member functions.

Check your progress/ Self assessment questions- 2

Q5. follows top-down approach programming and follows


bottom-up approach of programming.

Q6Structured Programming does not support data hiding. (TRUE / FALSE ).

Q7. What is the meaning of operator precedence and associativity?

Page 7 of 223
Q8. All concepts of OOP's can only be realized in C++ with the help of data type.

1.6.4 Input/ Output using C++


There is a difference in the way you accept input in C++ as compared to C. C++ programming
language uses the notion of streams to accept input and pass output to standard devices. The default or
standard input device is keyboard and standard output device is monitor. You can also use redirection
to change the default input and output streams. You will learn about advanced input and output
streams in lesson 15 of this SLM. In this section you will learn to accept input and display output
using two basic objects called cin and cout that belongs to iostream class. You will learn about classes
and objects later in this SLM. In order to accept input and display output using iostream, you need to
include "iostream.h" header file in your program.
#include<iostream.h>
cin- cin is the object used to accept input from the standard input device which by default is
keyboard.
The operator used with cin to accept input is >>. Working of >> operator with cin object is also
explained in lesson 15. You can accept input of any variable using cin object as follows;
cin>>Var_Name;
You don't have to specify the data type of the variable as you accept input. You can also accept input
of multiple variables using single statement as follows:
cin>>var1>>var2 ;
cout- cout is the object used to pass output to the standard output device which by default is monitor.
The operator used with cout to pass output is <<. You can pass two types of information to the output
device:
1. Constant- constant information is passed to output device using double quotes as follows:
cout<<"WELCOME TO IKGPTU";
Output device will display this constant information on the monitor.
2. Variable- variable information is passed to output device without the use of any quotes as follows:
cout<<Var_Name;
You can pass multiple constants and variables using single statement as follows:
cout<<"Sum of "<<a<<" and "<<b<<" is "<<sum;
'a', 'b' and 'sum' are three variables in the last statement.

Program- 1

Page 8 of 223
Simple program to add two numbers in C++ (without using classes)
#include < iostream.h > // for the use of iostream
#include < conio.h >
void main ()
{
int a , b , sum ;
cout <<"Enter first number :- " ; // constant information
cin>>a;
cout <<"Enter second number :- " ; // constant information
cin>>b;
sum = a + b ;
cout<<"sum of "<<a<<" , "<<b<<" is "<<sum ; // constant and variable information
return;
}

1.6.5 Difference between C and C++ programming languages


C Programming Language C++ Programming Language
C is a structural programming language. C++ is an object oriented programming
language.
Emphasis is logic and not on data. Emphasis is on data rather than procedure.

Functions are the fundamental building blocks. Objects are the fundamental building
blocks.
Variables can only be declared at the beginning Variables can be declared anywhere inside
of any function. the function.
Data hiding in not provided in C. Data can be hidden from external access.

C used top down approach. C++ used bottom up approach

scanf() and printf() functions are used for cin and cout are used for standard input and
standard input and output respectively. output respectively.
C does not provide the namespace feature. C++ provides the namespace feature.

C is a middle level language. C++ is a high level language.

Page 9 of 223
Programs are divided into functions. Programs are divided into classes that
contains both data and functions.
C doesn’t support exception handling. C++ supports exception handling.

Check your progress/ Self assessment questions- 3

Q9. Explain the roles of cin and cout objects of iostream class.

10. Variables can only be declared at the beginning of any function in C programming language. (
TRUE / FALSE ).

Q11. C++ is a middle level language. ( TRUE / FALSE )

1.7 Summary
The early software paradigms failed to keep the pace with the change in user requirement that keeps
on changing at rapid pace. After a series of deliberations most of the researchers came to a conclusion
that your programming language must support maintainability, reusability, openness, portability and
security to survive. The software evolution over decades is viewed as layered growth. Initially the
programmers used to write the absolute machine code that was directly understood by the computer.
With assembly programming languages, the program was compiled in two phases. Assembly code
was converted into machine code and then executed. Then came procedural and structural model. C
programming language is the most popular structural language. But structural programming failed to
address the key issues like maintainability and reusability. Then came the object oriented
programming languages. Object oriented programming is an extension of structural programming. It
addressed all the weaknesses of structural programming and became popular among masses.
Keywords are the reserved words in any programming that have pre-defined meaning and cannot be
used as identifiers. Operators are used to perform a set of operations on operands. The operators with
higher precedence are evaluated first as compared to other operators. In case two operators have same
precedence, they are evaluated in the order of their associativity. A new user defined data type "class"
is introduced which is the backbone of C++. All concepts of OOP's can only be realized using a class.

Page 10 of 223
Accepting of input and displaying of output can be achieved in C++ using two basic objects called cin
and cout that belongs to iostream class. You need to include "iostream.h" header file in your program
to use objects of iostream class. cin is the object used to accept input from the standard input device
which by default is keyboard. cout is the object used to pass output to the standard output device
which by default is monitor.

1.8 Glossary
Encapsulation-Encapsulation means binding of data and functions (coding) in a single type.
Inheritance-It lets you create a new class by re-using or inheriting the features of already existing
class and adding new features to the same.
Data hiding- restricting the access of data members using private access specifier directly from
outside the definition of the class.
Abstraction- It is used to reduce the complexity and improve the performance. Abstraction is also a
process of creating some abstract object from a class that depicts a real life entity and hiding un-
necessary implementation details from user.
Polymorphism- Polymorphism is also known as overloading. You can achieve function overloading
or function polymorphism by creating multiple function definitions with the same name that are
different in respect to number of arguments or type of arguments. You can also redefine the already
defined operators and make them work or class objects like they work on variables of any data type.
OOP- Object oriented programming is based on the key features like inheritance, polymorphism,
encapsulation, abstraction and data hiding. It is about creating abstract objects belonging to some
class type.
Structural programming-Structured Programming is also known as procedural programming in which
the code is written in self contained functions.
Class- A class is a user defined data type that is a collection or binding of data members and member
functions.
Object- It is an instance of a class that represents an entity of real life.

1.9 Answers to check your progress/self assessment questions


1.
a. Maintainability.
b. Reusability.
c. Openness.
d. Portability.
e. Security.

Page 11 of 223
2.
a. Machine language
b. Assembly language
c. Structural programming language
d. Object oriented programming language
3. Inheritance lets you create a new class by re-using or inheriting the features of already existing
class and adding new features to the same. Inheritance helps you to improve the reusability of your
code by re-using already tested classes. It also helps to reduce a lot of programming effort and also
improves the performance.
4. Virtual function.
5. structured programming, object oriented programming.
6. TRUE.
7. The operators with higher precedence are evaluated first as compared to other operators in a given
expression. In case two operators have same precedence, they are evaluated in the order of their
associativity.
8. class.
9. cin is the object of iostream class used to accept input from the standard input device which by
default is keyboard.The operator used with cin to accept input is >>. cout is the object of iostream
class used to pass output to the standard output device which by default is monitor.The operator used
with cout to pass output is <<. You can pass both constant and variable information to the output
device using cout.
10. TRUE.
11. FALSE.

1.10 References/ Suggested Readings


1. Balagurusamy, Object Oriented Programming with C++, 3rd Edition, Tata McGraw-Hill
Education, 2006.
2. Lafore R, Object Oriented Programming in C++, 4th Edition Waite Group, 2002.
3. R. S. Salaria, Mastering Object-Oriented Programming with C++, Salaria Publishing House.

1.11 Model questions


1. Explain the evolution of programming languages.
2. Explain the use of cin and cout objects with the help of an example each.
3. Write the differences between structural and object oriented programming.
4. Write a program to accept two numbers and display their average using cin and cout.
5. Explain the key features of object oriented programming in detail.

Page 12 of 223
Lesson- 2 Fundamentals of structure
Structure
2.0 Objective
2.1 Introduction
2.2 Structure
2.3 Declaration of a structure
2.3.1 Creating objects of a structure
2.4 Initializing Structure Objects
2.5 Accessing the members of the structure object
2.6 Summary
2.7 Glossary
2.8 Answers to check your progress/self assessment questions
2.9 References/ Suggested Readings
2.10 Model questions

2.0 Objective
After studying this lesson, students will be able to:
1. Define structure data type.
2. Declare user defined structures.
3. Create objects of structure data type.
4. Access members of structure object.
5. implement programs to create basic structures.

2.1 Introduction
Structures is an important user-defined data type in C++. Complex entities can be represented using
structures. Structure can also be used with C programming language. Structure is also used to
represent data bases. Structure helps in reducing the complexity of managing data in C++
programming language. Data structure elements can also be represented in memory using structures.
In this lesson you will learn the fundamentals of structure, declaration of structure and how you can
create objects of a structure. Members of the structure object cannot be directly accessed using their
name. This lesson also discussed the two methods used to access each member of the structure object
individually. In the end, you will implement programs to access members of structure objects.

2.2 Structure
Structure is a user defined data type. It can perform most of the tasks that can be performed by class
data type that forms the basis of object oriented programming, but there are some fundamental

Page 13 of 223
differences between structure and class. A class is a user defined data type which is a collection of
data members and member functions and is discussed later in this SLM.
Formally a structure is a collection of non-similar data elements that are grouped using a single
identifier.
You must be familiar with arrays. Recall that array is a collection of similar type of data elements.
Also array is a derived data type and structure is a user-defined data type. Structures are used to
represent data items that have more than one attribute. Consider that you are writing a program to
manage hotel booking record. For that you need to record all attributes of the entity hotel booking.
Some of the most basic attributes for a hotel booking are as follows:

Hotel Booking
Room number
Name of the customer
Customers address
Mobile number

You cannot save details of hotel booking using a variable of any default data type as it has multiple
attributes. Also you cannot use array for the same as array can only be used to save elements of same
data type and in this case the members need to be saved are using different data types.

Consider the following entity and the attributes needed to save it:
Employee
Employee name
ID of the employee
Monthly salary of the employee

2.3 Declaration of a structure


Before you can create objects or variables of user defined data type "structure", you need to declare or
prototype a structure. In declaration of a structure, you provide a name to the structure which then
becomes a user defined data type and the same is used to create the objects. You also provide the
declarations of various members of that structure in the member list. Following is the syntax used to
create a structure type:
struct Stucture_Name
{
// member list including the data types and identifiers
};
Consider the following example of structure book:

Page 14 of 223
struct book
{
char book_title[ 30 ] ;
int isbn ;
int price ;
char author_name[ 30 ] ;
char publisher[30] ;
};
In the last example a structure named "book" is prototyped. It means that you have created a new user
defined data type called "book" and now you can create objects of type "book" just like any default
data type. Structure consists of 5 members out of which 3 are of string type [array of characters] and 2
are of integer type. Proper identifiers are assigned to each member that will be used to access each
member individually.
You are not allowed to define or initialize any of the members of the structure when you proto
type the structure.

Check your progress/ Self assessment questions- 1

Q1. Structure is a data type.

Q2. Define structure.

Q3. Array is a collection of type of data elements and it is a data type.

Q4. Before you can create objects of user define data type "structure", you need to
a structure.

Q5. While declaration of a structure, you provide a to the structure which then becomes a
user defined data type

2.3.1 Creating objects of a structure


Declaring or prototyping a structure is only creating a new user defined data type. In order to make
use of it, you need to create objects of the same. Object is an instance of structure. What does an
instance means? When you create an object of structure type, memory is allocated to the structure

Page 15 of 223
object just like memory is allocated to any variable of default data type. Once you create an object of
structure type, an instance of all members of structure is created in memory that can be accessed using
the object.
You can create or declare an object of the structure as follows:
Structure_Name Object_list ;
For example,
book obj1 , obj2 ; // statement is used to create 2 objects of structure book.
You can also create objects of a structure along with the prototype of that structure itself:
struct book
{
char book_title[ 30 ] ;
int isbn ;
int price ;
char author_name[ 30 ] ;
char publisher[30] ;
} obj1 , obj2 ;
Again two objects of the "book" structure are declared along with the prototype of the same.

2.4 Initializing Structure Objects


You can initialize all or some of the members of the structure object you declare. It is not mandatory
to initialize all members of the structure object. You have already seen in the last section, how to
create structure objects without any initialization. It is often desirable to initialize some members
when you create objects of a structure. For example, there are situations when members like school
name, address, station, department mostly consists of same values. In such a case, it is better to
initialize them with some common value rather than accepting input from the user again and again.
Consider the following prototype of "student" structure and initialization of its objects:
struct student
{
int class_no ;
char branch [ 20 ] ;
int roll_no ;
char name [ 30 ] ;
};
student obj1 = { 12 , "kapurthala" } ;
In the last example, a structure "student" is prototyped with 4 members. Also an object of the same is
declared and initialized using the following statement:
student obj1 = { 12 , "kapurthala" } ;

Page 16 of 223
Only two parameters are passed for initializing the members of the object "obj1". First parameter "12"
is assigned to member "class_no" and second parameter "kapurthala" is assigned to member "branch".
You can also initialize all members of the structure object for which you need to pass 4 parameters.

Check your progress/ Self assessment questions- 2

Q6. Object is called an of structure.

Q7. What happens when you create an object of structure type?

Q8. Write the syntax to declare an object of the structure.

Q9. You cannot create objects of a structure along with the prototype of that structure itself. ( TRUE /
FALSE )

Q10. You have to initialize all members of the structure object you declare. ( TRUE / FALSE )
Q11. Why is it sometimes desirable to initialize members of structure?

2.5 Accessing the members of the structure object


A structure is a collection of non-homogeneous data elements called members of the structure. When
you create an object of the same structure, an instance of all members is created in memory. You can
access each member individually using the object they belong to. When you create more than one
object, multiple and separate instances of members is created in memory and each belongs to a
dedicated object. Before you learn the concept of accessing members of structure object, it is
important that you understand the memory allocation scheme of structure object. Consider the
following structure prototype for an example:
struct employee
{
char name [ 30 ] ;

Page 17 of 223
int id ;
int salary ;
};
The above statements are used to prototype a structure named "employee" that consists of 3 members.
You can create or declare an object of the same using the following statement:
employee obj1 ;
How much memory is allocated to a single instance of structure object? When you declare an
object of class structure, an instance of all members is created in memory and each member is
allocated individual space in memory. For instance, the structure above consists of 3 members and the
memory needed by each member is:
char name [ 30 ] = 30 bytes
int id = 2 bytes
int salary = 2 bytes
Total memory needed to create one instance of "employee" object is sum of memory needed by all
members of the structure together which is 34 bytes. So, memory allocated to one object of structure
"employee" will be 34 bytes.

Figure 2.1 Memory needed by one instance of "employee" object

Members cannot be accessed directly using their identifiers or names. They belong to an instance of
one object of a structure and can only be accessed using that object only. Also as already stated you
can create multiple instances of the same by creating multiple objects. You can access each member
of the structure object using a dot or membership operator. Syntax to access individual member using
structure object is as follows:
Object_Name . Member_Name ;
In the statement above, Object_Name refers to valid identifier of a structure object. "." is called the
dot or membership operator followed by the valid identifier of one of the member of the structure
itself. For example,
employee obj1 ;
cin>>obj1.id ;
First statement is used to create an object with identifier "obj1" of structure "employee". The second
statement is used to access member "id" that belongs to an instance of "obj1" using the membership
operator. Similarly you can access other members of the object as well. If you create two objects of
one structure using the following statement:

Page 18 of 223
employee obj1 , obj2 ;
Two separate instances of each member of structure is created and you can access same member for
two different instances using the following statement:
cin>>obj1.id ;
cin>>obj2.id ;
First statement is used to access the member "id" that belongs to the instance "obj1" and second
statement is used to access the member "id" that belongs to the instance "obj2".

Check your progress/ Self assessment questions- 3

Q12. You can access each member using the they belong to..

Q13. How much memory is allocated to a single instance of structure object?

Q14. Members cannot be accessed using their identifiers or names and you can access
each member of the structure object using a operator.

Program 1
To implement structure data type
// header files
#include<iostream.h>
#include<conio.h>
// declaration of book structure
struct book
{
char book_title[ 30 ] ;
int isbn ;
int price ;
char author_name[ 30 ] ;
char publisher[30] ;
};
Void main( )
{
// object of structure book

Page 19 of 223
book obj ;
// accessing each element of object for input
cout<<" \n Enter details of book ";
cout<<" \n Enter title of the book :- " ;
cin>>obj.book_title ;
cout<<" \n Enter isbn number :- " ;
cin>>obj.isbn ;
cout<<" \n Enter price of the book :- " ;
cin>>obj.price ;
cout<<" \n Enter the author name for the book :- " ;
cin>>obj.author_name;
cout<<" \n Enter the publisher of the book :- " ;
cin>>obj.publisher;
// accessing each element of object for output
cout<<" \n Details of employee " ;
cout<<" \n Book Title :- " <<obj.book_title;
cout<<" \n ISBN number :- " <<obj.isbn ;
cout<<" \n Book Price :- " <<obj.price ;
cout<<" \n Author Name :- " <<obj.author_name;
cout<<" \n Publisher Name :- " <<obj.publisher;
getch ( ) ;
}
Output:
Enter details of book
Enter title of the book :- mathematics-1
Enter isbn number :- 1234
Enter price of the book :- 500
Enter the author name for the book :- seema
Enter the publisher of the book :- ikgptu
Details of employee
Book Title :- mathematics-1
ISBN number :- 1234
Book Price :- 500
Author Name :- seema
Publisher Name :- ikgptu

Program 2

Page 20 of 223
To implement the initialization of structure object
// header files
#include<iostream.h>
#include<conio.h>
// declaration of employee structure
struct student {
int class_no ;
int roll_no ;
int age ;
};
Void main( )
{
// objects of student structure
student obj1 = { 12 } , obj2 = { 12 } ;
// accessing each element of object for input
cout<<" \n Enter details of student no. 1 ";
cout<<" \n Enter student roll number :- " ;
cin>>obj1.roll_no ;
cout<<" \n Enter student age :- " ;
cin>>obj1.age ;
cout<<" \n Enter details of student no. 2 ";
cout<<" \n Enter student roll number :- " ;
cin>>obj2.roll_no ;
cout<<" \n Enter student age :- " ;
cin>>obj2.age ;
// accessing each element of object for output
cout<<" \n Details of student no. 1 " ;
cout<<" \n Studentclass :- " << obj1.class_no ;
cout<<" \n Student roll number :- " << obj1.roll_no ;
cout<<" \n Student age :- " <<obj1.age ;
cout<<" \n Details of student no. 2 " ;
cout<<" \n Studentclass :- " << obj2.class_no ;
cout<<" \n Student roll number :- " << obj2.roll_no ;
cout<<" \n Student age :- " <<obj2.age ;
getch ( ) ;
}
In the last program, two objects of structure "student" are initialized using the following statement:

Page 21 of 223
student obj1 = { 12 } , obj2 = { 12 } ;
"student" structure consists of three members and only one parameter is passed for both the objects. It
means that only the first member for both objects, i.e. class_no is initialized. For the other two
members input is accepted from the user.

Output:
Enter details of student no. 1
Enter student roll number :- 18
Enter student age :- 17
Enter details of student no. 2
Enter student roll number :- 22
Enter student age :- 18
Details of student no. 1
Studentclass :- 12
Student roll number :- 18
Student age :- 17
Details of student no. 2
Studentclass :- 12
Student roll number :- 22
Student age :- 18

2.6 Summary
Structure is a user defined data type. Formally a structure is a collection of non-similar data
elements that are grouped using a single identifier. Structures are used to represent data items that
have more than attribute. Before you can create objects or variables of user define data type
"structure", you need to declare or prototype a structure. In declaration of a structure, you provide a
name to the structure which then becomes a user defined data type and the same is used to create the
objects. You also provide the declarations of various members of that structure in the member list.
Declaring or prototyping a structure is only creating a new user defined data type. In order to make
use of it, you need to create objects of the same. Object is an instance of structure. When you create
an object of structure type, an instance of all members of structure is created in memory that can be
accessed using the object.
You can initialize all or some of the members of the structure object you declare. It is not mandatory
to initialize all members of the structure object. You can access each member individually using the

Page 22 of 223
object they belong to. When you create more than one object, multiple and separate instances of
members is created in memory and each belongs to a dedicated object. When you declare an object of
class structure, an instance of all members is created in memory and each member is allocated
individual space in memory. Total memory needed to create one instance of structure object is sum of
memory needed by all members of the structure together. Members cannot be accessed directly using
their identifiers or names. They belong to an instance of one object of a structure and can only be
accessed using that object only. You can access each member of the structure object using a dot or
membership operator.

2.7 Glossary
Structure- Structure is a collection of non-similar data elements called members that are grouped
using a single identifier.
Array- It is a collection of similar data elements that are stored contiguously in memory.
Class- It is a collection of data members and member functions.
Dot operator- It is used to access a member of structure object.

2.8 Answers to check your progress/self assessment questions


1. user defined.
2. Structure is a collection of non-similar data elements called members that are grouped using a
single identifier.
3. similar, derived.
4. Prototype / declare.
5. name / identifier.
6. instance.
7. Once you create an object of structure type, an instance of all members of structure is created in
memory that can be accessed using the object.
8. Structure_Name Object_list;
9. FALSE.
10. FALSE.
11. There are situations when members like school name, address, station, department mostly consists
of same values. In such a case, it is better to initialize them with some common value rather than
accepting input from the user again and again.
12. object.
13. When you declare an object of class structure, an instance of all members is created in memory
and each member is allocated individual space in memory. Total memory needed to create one
instance of structure object is sum of memory needed by all members of the structure together.
14. directly, dot / membership.

Page 23 of 223
2.9 References/ Suggested Readings

1. Balagurusamy, Object Oriented Programming with C++, 3rd Edition, Tata McGraw-Hill
Education, 2006.
2. Lafore R, Object Oriented Programming in C++, 4th Edition Waite Group, 2002.
3. R. S. Salaria, Mastering Object-Oriented Programming with C++, Salaria Publishing House.

2.10 Model questions

1. Define structure with the help of an example.


2. What is an array and how it is different from structure?
3. Why you create objects of structure? Explain two methods to create object of a structure.
4. How can you initialize members of structure?
5. How can you access each member of the structure object individually?

Lesson- 3 Advanced concepts- Structure


Structure
3.0 Objective
3.1 Introduction

Page 24 of 223
3.2 Array of structure
3.3 Structure with pointer
3.4 Nested Structure
3.5 Functions and structures
3.6 Union
3.7 Difference between union and structure
3.8 Summary
3.9 Glossary
3.10 Answers to check your progress/self assessment questions
3.11 References/ Suggested Readings
3.12 Model questions

3.0 Objective
After studying this lesson, students will be able to:
1. Create arrays of structure objects
2. Use pointer as structure object.
3. Pass structure object as argument to function.
4. Create a structure within another structure.
5. Define union data type.
6. Differentiate between structure and class.

3.1 Introduction
In the last lesson you learned the fundamental concepts of user defined data type called structure.
Structure is a collection of non-homogeneous data elements. Now you are familiar with the
declaration of structure type and initialization of members of structure object. Also in the last lesson
you saw how to access the individual members of structure using its object. In this lesson you will
learn implementation of advanced concepts related to structures. Also a new data type called union is
explained in this lesson.

3.2 Array of structure


A structure is practically used to represent complex data entities that have multiple attributes like
book, student, employee, product, etc. When you create large projects that may require you to create
such structures, it is guaranteed that it will be required to create and maintain large number of objects.
It is practically not feasible to create hundreds of objects with different identifiers. The best approach
is to create an array of structure objects. Each element in the array of structure objects will share the
same identifier and is accessed individually using its index number. Array is a collection of

Page 25 of 223
homogeneous data elements and each element in this case will represent one object of the structure.
One object in itself is a collection of non-homogeneous data elements.
Consider the following structure:
struct employee {
int id_no ;
int age ;
int salary ;
};
Total memory that is allocated to an object of this structure is ( 2 + 2 + 2 ) = 6 bytes. You can create
an array of objects for the same using the following statement:
employee obj [ 10 ] ;
The last statement is used to create an array of structure objects with 10 elements. Now that one object
takes 6 bytes in memory, an array of 10 objects will take 10 * 6 = 60 bytes in memory. Each element
in array which is an object will take 6 bytes of memory.
You can access elements of object array using the following statement:
obj [ 5 ]. id_no;
The last statement is used to access the member "id_no" of the object having index 5 in the array
"obj".

Program 1
To create an array of structure objects
// header files
#include<iostream.h>
#include<conio.h>
// declaration of employee structure
struct employee {
int id_no ;
int age ;
int salary ;
};
Void main( )
{
int count ;
// array of objects
employee obj [ 2 ] ;
// accessing each element of object using arrays for input
for ( count = 0 ; count < 2 ; count++ )

Page 26 of 223
{
cout<<" \n Enter details of employee no. " << count + 1 ;
cout<<" \n Enter employee number :- " ;
cin>>obj[count].id_no ;
cout<<" \n Enter employee age :- " ;
cin>>obj[count].age ;
cout<<" \n Enter employee salary :- " ;
cin>>obj[count].salary ;
}
// accessing each element of object using arrays for output
for ( count = 0 ; count < 2 ; count++ )
{
cout<<" \n Details of employee no. " << count + 1 ;
cout<<" \n Employee number :- " << obj[count].id_no ;
cout<<" \n Employee age :- " << obj[count].age ;
cout<<" \n Employee salary :- " << obj[count].salary ;
}
getch ( ) ;
}
Output:
Enter details of employee no. 1
Enter employee number :- 1
Enter employee age :- 25
Enter employee salary :- 20000
Enter details of employee no. 2
Enter employee number :- 1
Enter employee age :- 24
Enter employee salary :- 18000
Details of employee no. 1
Employee number :- 1
Employee age :- 25
Employee salary :- 20000
Details of employee no. 2
Employee number :- 1
Employee age :- 24
Employee salary :- 18000

Page 27 of 223
3.3 Structure with pointer
Pointer is a variable used to store the address of another variable or reference. Structure is a user
defined data type. You have seen how to create objects of a structure type. Objects of a structure are
just like any variable of a default data type. Pointer can also be used to refer to an object of structure
type. There is difference in the way you will access each member of the object using pointer as
compared to accessing simple variable using pointer. You can create a pointer of employee structure
using the following statement:
employee * ptr;
Then the same pointer can be used to save the address of employee object using the following
statement:
ptr = & obj1 ;
There are two syntaxes that you can use to access each member of the structure object individually
using the pointer variable. One makes the use of " -> " operator as shown in the figure below:
ptr -> id_no ;
Second is to make use of " *. " operator as shown in the figure below:
( * ptr ). id_no ;
Precedence of the dot operator is more than that of the de-reference operator and hence the de-
reference operator is given inside the bracket because you need to de-refer the pointer variable first
and then apply the dot operator on it.
Program 2
To implement structure type using pointer
// header files
# include < iostream.h >
# include < conio.h >
// declaration of employee structure
struct employee {
int id_no ;
int age ;
int salary ;
};

Void main( )
{
// object of structure employee
employee obj1 ;
// pointer of structure employee type
employee * ptr ;

Page 28 of 223
// assigning address of employee object to employee pointer
ptr = & obj1 ;
// accessing object members using " -> " operator
cout<<" \n Enter details of employee " ;
cout<<" \n Enter employee number :- " ;
cin>>ptr->id_no ;
cout<<" \n Enter employee age :- " ;
cin>>ptr->age ;
cout<<" \n Enter employee salary :- " ;
cin>>ptr->salary ;
// accessing object members using " *. " operator
cout<<" \n Details of employee " ;
cout<<" \n Employee number :- " << ( *ptr ).id_no ;
cout<<" \n Employee age :- " << ( *ptr ).age ;
cout<<" \n Employee salary :- " << ( *ptr ).salary ;
getch ( ) ;
}
Output:
Enter details of employee
Enter employee number :- 111
Enter employee age :- 28
Enter employee salary :- 25000
Details of employee
Employee number :- 111
Employee age :- 28
Employee salary :- 25000

Check your progress/ Self assessment questions- 1

Q1. Each elements in the array of structure objects share the same and is accessed
individually using its number.

Q2. Pointer is a variable used to store the of another variable or reference.

Q3. Two techniques are available to access members of structure using pointer object. ( TRUE /
FALSE )

Page 29 of 223
3.4 Nested Structure
Nested structure is an interesting concept. Nested structure lets you prototype a structure within the
prototype of another structure. Also you can implement nested structure by making an object of one
structure member of another structure.

Need of nested structure arises when one member of structure itself is a structure. Consider the
following example:
struct marks
{
int subj1 ;
int subj2 ;
};
struct student
{
int roll_no ;
int class_no ;
marks mobj ;
};
"marks" is a member of structure "student". But "marks" is a complex entity and it can only be
represented with the help of structure. Hence the prototype of structure "student" contains the object
of structure "marks".
You can access the member of structure marks using the object of structure student using the double
dot operator as shown in the statement below:
obj1. mobj. subj1 ;

Program 3
To implement the concept of nested structure
// header files
# include < iostream.h >
# include < conio.h >
// declaration of marks structure
struct marks
{
int subj1 ;
int subj2 ;
};
// declaration of student structure

Page 30 of 223
struct student
{
int roll_no ;
int class_no ;
// object of structure marks
marks mobj ;
};
Void main( )
{
// object of structure student
student obj1 ;
// accessing object members for input
cout<<" \n Enter details of student " ;
cout<<" \n Enter student roll number :- " ;
cin>>obj1.roll_no ;
cout<<" \n Enter student class :- " ;
cin>>obj1.class_no ;
// accessing members of nested structure
cout<<" \n Enter marks in first subject :- " ;
cin>>obj1.mobj.subj1 ;
cout<<" \n Enter marks in second subject :- " ;
cin>>obj1.mobj.subj2 ;
// accessing object members for output
cout<<" \n Details of student " ;
cout<<" \n Student roll number :- " << obj1.roll_no ;
cout<<" \n Student class :- " << obj1.class_no ;
cout<<" \n Marks in first subject :- " << obj1.mobj.subj1 ;
cout<<" \n Marks in second subject :- " << obj1.mobj.subj2 ;
getch ( ) ;
}
Output:
Enter details of student
Enter student roll number :- 12
Enter student class :- 11
Enter marks in first subject :- 90
Enter marks in second subject :- 93
Details of student

Page 31 of 223
Student roll number :- 12
Student class :- 11
Marks in first subject :- 90
Marks in second subject :- 92

3.5 Functions and structures


You can also pass object of a structure as argument to a function. Normally a pointer object is passed
as argument to a function to improve the performance. Size of a structure object can be extremely
large in memory. When you pass a very large object as actual argument, you also need a large formal
argument to receive the same. This problem can be overcome by passing pointer object as argument
which takes constant space in memory irrespective of the size of object in memory.

Program 4
To pass pointer object of a structure as argument to a function
// header files
# include < iostream.h >
# include < conio.h >
// declaration of employee structure
struct employee {
int id_no ;
int age ;
int salary ;
};
// function prototype
void display ( employee * ) ;
void main( )
{
// object of structure employee
employee obj1 ;
// accessing object members for input
cout<<" \n Enter details of employee " ;
cout<<" \n Enter employee number :- " ;
cin>>obj1.id_no ;
cout<<" \n Enter employee age :- " ;
cin>>obj1.age ;
cout<<" \n Enter employee salary :- " ;
cin>>obj1.salary ;

Page 32 of 223
// function call statement
display ( & obj1 ) ;

getch ( ) ;
}
// definition of function display
void display ( employee * ptr )
{
// accessing object members using " *. " operator
cout<<" \n Details of employee " ;
cout<<" \n Employee number :- " << ( *ptr ).id_no ;
cout<<" \n Employee age :- " << ( *ptr ).age ;
cout<<" \n Employee salary :- " << ( *ptr ).salary ;
}
Output:
Enter details of employee
Enter employee number :- 11
Enter employee age :- 35
Enter employee salary :- 30000
Details of employee
Employee number :- 11
Employee age :- 35
Employee salary :- 30000

Check your progress/ Self assessment questions- 2

Q4. What is a nested structure?

Q5. You can access the member of nested structure using dot operator.

Q6. Why you pass pointer to structure object as argument to a function?

Page 33 of 223
3.6 Union
Union is similar to structure. It is a user defined data type. Union refers to the representation of
multiple members using a single memory space. In case of union, only one of its member is active at
one time. We normally use union when based on some condition only one of its member can be valid.
Declaration of union is same as that of structure, except that you use union keyword instead of struct.
union union_name
{
// member list
};
A union is different from structure in principle. Total memory allocated to a union object is the
memory needed by its largest member. Consider the following union for example,
union value
{
int ino ;
float fno ;
};
If you create an object of union "value", 4 bytes of memory will be allocated to it. You can save value
of only one of the two members at one time.

Program 5
To implement the concept of union
// header files
# include < iostream.h >
# include < conio.h >
// declaration of union value
union value
{
int ino ;
float fno ;
};
Void main( )
{
// object of union value

Page 34 of 223
value obj1 ;
// accessing object members for input
cout<<" \n Enter details of value " ;
cout<<" \n Enter integer value :- " ;
cin>>obj1.ino ;
cout<<" \n Enter float value :- " ;
cin>>obj1.fno ;
// accessing object members for output
cout<<" \n Details of value " ;
cout<<" \n Integer value :- " << obj1.ino ;
cout<<" \n Float value :- " << obj1.fno ;
getch ( ) ;
}
Output:
Enter details of value
Enter integer value :- 12
Enter float value :- 12.56
Details of value
Integer value :- -2621
Float value :- 12.56

Value of integer variable "ino" was overwritten by float variable "fno". When you try to access the
value using "ino", it gives unexpected answer.

3.7 Difference between union and structure


Union Structure
1. Declared using "union" keyword. 1. Declared using "struct" keyword.
2. Memory allocated to object of union is 2. Memory allocated to object of structure is sum
equivalent to memory needed by its largest of memory needed by all members of a structure.
member.
3. Value for only member is valid at one time. 3. Values for all members are valid at one time.
4. All members of a union object share the same 4. Individual memory is allocated to each
memory space. member of structure object.
5. You can initialize a union object only with the 5. You can initialize one or more members of an
type of the first member of the union. object of structure.

Page 35 of 223
Check your progress/ Self assessment questions- 2

Q7. Union refers to the representation of multiple members using a memory space.

Q8. Total memory allocated to a union object is the memory needed by its member.

Q9. You can initialize a union object only with the type of the member of the union.

Q10. By default all members of a structure are public members. ( TRUE / FALSE )
Q11. A special pointer called "this" works with structure type. "This" pointer refers to an object of the
same structure that places a call to its member function. ( TRUE / FALSE )

3.8 Summary
A structure is practically used to represent complex data entities that have multiple attributes. It is
practically not feasible to create hundreds of objects with different identifiers. The best approach is to
create an array of structure objects. Each element in the array of structure objects share the same
identifier and is accessed individually using its index number. Pointer is a variable used to store the
address of another variable or reference. Pointer can also be used to refer to an object of structure
type. There are two syntaxes that you can use to access each member of the structure object
individually using the pointer variable. One makes the use of " ->“ operator and second is to make
use of " *. " operator.
Nested structure lets you prototype a structure within the prototype of another structure. Also you can
implement nested structure by making an object of one structure member of another structure.
You can also pass object of a structure as argument to a function. Normally a pointer object is passed
as argument to a function because pointer object as argument takes constant space in memory
irrespective of the size of object in memory.
Union is a user defined data type. Union refers to the representation of multiple members using a
single memory space. In case of union, only one of its member is active at one time. Total memory
allocated to a union object is the memory needed by its largest member.

3.9 Glossary
Structure- It is a user defined data type which is collection of non-homogeneous data elements.
Union- It is a user defined data type that refers to the representation of multiple non-homogeneous
members using a single memory space.
Pointer- A variable used to store the address of another variable or reference.
Nested structure- Nested structure is one which is prototyped within the prototype of another structure

Page 36 of 223
Function- Block of executable statements.
Class- Collection of data members and member functions.
Array- It is a collection of homogeneous data elements that are stored contiguously in memory.

3.10 Answers to check your progress/self assessment questions

1. identifier , index.
2. address.
3. TRUE
4. Nested structure is one which is prototyped within the prototype of another structure. Also you can
create a nested structure by declaring an object of one structure as member of another structure.
5. double.
6. A pointer object is passed as argument to a function to improve the performance. Size of a structure
object can be extremely large in memory and you need a large formal argument to receive the same.
Passing pointer object as argument is efficient as it takes constant space in memory irrespective of the
size of object in memory.
7. single.
8. largest.
9. first.
10. TRUE.
11. FALSE.

3.11 References/ Suggested Readings


1. Balagurusamy, Object Oriented Programming with C++, 3rd Edition, Tata McGraw-Hill
Education, 2006.
2. Lafore R, Object Oriented Programming in C++, 4th Edition Waite Group, 2002.
3. R. S. Salaria, Mastering Object-Oriented Programming with C++, Salaria Publishing House.

3.12 Model questions


1. Write the differences between structure and union.
2. Write the differences between structure and class.
3. Write a program to pass structure object as argument to a function.
4. What is a nested structure? Explain it with a help of an example.
5. What is the advantage of creating array of structure objects? Write a program to implement the
same.

Page 37 of 223
Lesson- 4 Fundamentals of class
Structure
4.0 Objective
4.1 Introduction
4.2 Structures in C and classes in C++

Page 38 of 223
4.3Class Declaration
4.3 Access specifiers
4.4 Array within a class
4.5 Data hiding and encapsulation
4.7 Difference between structure and class
4.8 Summary
4.9 Glossary
4.10 Answers to check your progress/self assessment questions
4.11 References/ Suggested Readings
4.12 Model questions

4.0 Objective
After studying this lesson, students will be able to:
1. Define class data type.
2. Declare a class type.
3. Explain the concept of private and public access specifiers.
4. Create an array within a class.
5. Define data hiding.

4.1 Introduction
In this lesson you will learn about another user defined data type called class. Data type class is
introduced in C++ and was not part of C programming language. Eventually it is class data type that
forms the basis of object oriented programming. You are able to implement all concepts like data
hiding, encapsulation, inheritance, polymorphism, abstraction using class data type. The lesson begins
by revisiting the concept of structures in C. In this lesson you will learn the basic concepts of class
data type and how you can prototype the same. The lesson also discusses the concept of data hiding
and how it can be implemented using class.

4.2 Structures in C and classes in C++


A structure in C programming language is collection of heterogeneous data elements. It is used in C
programming language to group together related data elements or it is used to represent data entities
having multiple attributes. The syntax used for declaring a structure, creating objects of the same and
accessing individual members is same as discussed earlier in SLM for C++ programming language.
Structures in C are often compared to classes in C++ but there are major differences between the two.
A structure in C programming is used to represent an entity with multiple attributes or members and
you can access each member of the object in C using the dot operator. But C programming does not
allow you to operate on objects of structure like you can operate on variables of default data type. For
example, you can apply all mathematical operators on variables of integer type in C, but you cannot
apply mathematical operators on structure objects in C. In C++ you will learn about the concept of

Page 39 of 223
operator overloading using which you will be able to apply mathematical operations on class object
and re-define the already existing operators in C++.
Also as stated, structure in C is a collection of heterogeneous data elements. C programming does not
allow you to restrict access to members of structure. You can access all members of structures in C.
C++ lets you restrict access to the members of a class data type which is called the feature of data
hiding. Beside these two major differences, there are many more extensions provided by C++
programming language to classes over structures in C.

4.3Class Declaration
Biggest introduction or change in C++ programming is Class data type. C++ programming language
is often called C with classes. There are lots of similarities between classes in C++ and structures in C
and is considered to be an extension of structures in C.
Class is a user defined data type which is a collection of data members and member functions.
Structures in C were used to bind the related data items and did not include the functions. C++ lets
create and use classes just like any other default data type. A class consists of two parts:
1. Class declaration or class member list.
2. Class member function definitions.
You can declare or prototype a class just as you prototype structures in C++. Structure is declared
using keyword struct and class is declared using the keyword class. When you declare a class, a new
abstract data type is created and you can use it just like any default data type. In class declaration,
class keyword is followed by the name of the class that acts as newly created abstract data type. It is
then followed by the body of the class or the member list. It includes the declarations of data members
and member functions of the class. Data members and member functions collectively are also referred
to as class members.
You can define a member function of the class just like you define any other function in C++.
Because the member function belongs to the class, scope resolution operator is used while defining
the member function to specify the ownership.
A class helps to achieve the objective of encapsulation. Binding of data members and member
functions together into a single class type is called encapsulation.
Following is the blueprint to declare a class
class Class_Name
{
// declaration of data members
// declaration of member functions
};
For example,
class student
{

Page 40 of 223
// data members
char name [ 30 ] ;
int class_no , roll_no , age ;
int marks_subj1 , marks_subj2 , avg ;

// member functions
void input_details ( ) ;
void compute_average ( ) ;
void display_details ( ) ;

};
You generally declare a class having some meaning. Once you declare a class, it becomes an abstract
data type and it's identifier is then used to create instances or objects of the same. In the last example,
"student" class is declared which becomes a newly created abstract data type. "student" class consists
of 7 data members and 3 member functions. The 3 member functions are declared as public and hence
can be accessed from outside the class. 7 data members are declared as private and cannot be accessed
from outside the class. You can access private data members of the class using the public member
functions.
Member functions of the class are only prototyped and should also be defined. Definition of member
functions of a class is discussed in the next lesson.

Prototyping a class only creates a new abstract data type. You need to create instance of the same to
make use of it. You can create instance of a class by declaring an object of the same. You can also
declare multiple objects of a class which then creates multiple instances of the data members of
class. C++ provides a special pointer using keyword "this" to represent an object or instance.
"This" pointer refers to an object that calls the member function of the class. Object declaration
and use of objects is discussed in lesson 6 of this SLM.
Check your progress/ Self assessment questions- 1

Q1. C programming does not allow you to operate on objects of structure like you can operate on
variables of data type.

Q2. C programming does not allow you to restrict to members of structure.

Q3. Define class.

Q4. When you declare a class in C++, a new data type is created and you can use it
just like any default data type.

Page 41 of 223
Q5. pointer refers to an object that calls the member function of the class.

4.4Access specifiers
There is another major difference between structures in C and classes in C++ and that is the concept
of data hiding. You can restrict the access to class members which is not possible to structures in C++.
You can declare class members inside the class declaration using two access specifiers called private
and public. Access specifier is used to specify the access rules for the class members.
Class members declared as private cannot be accessed from outside the class. Their scope is limited
only to the class body, whereas class members declared as public can be accessed from both inside
and outside the class. Generally the data members are declared as private and member functions are
declared as public. Data members are hidden from outside the class. They can only be accessed from
the member functions of the class.
Like the example given in section 4.2, the class members are declared without specifying the access
specifier. In C++, if you do not specify the access specifier when declaring a class, all class
members by default are private. Class declared in section 4.2 can be declared once again using
private and public access specifiers.
class student

{
private:
char name [ 30 ] ;
int class_no , roll_no , age ;
int marks_subj1 , marks_subj2 , avg ;

public:
void input_details ( ) ;
void compute_average ( ) ;
void display_details ( ) ;

};
4.5 Array within a class
You already know that array is a derived data type. Array is a collection of homogeneous data
elements that are stored contiguously in memory. C++ lets you create array within the declaration of
class. It means that you can declare an array as data member of class. It means you can create a data
member of derived type as class member.
Declaring an array is simple. You need to specify the size of the array next to array identifier when
declaring it. You can declare an array using the following syntax:
Data_Type Array_Name [ size ] ;
For example,
int students [ 10 ] ;

Page 42 of 223
Example or creating a class having array as data member
class student

{
private:
char name [ 30 ] ;
int class_no , roll_no , age ;
// array as data member
int marks[5] ;

public:
void input_details ( ) ;
void compute_average ( ) ;
void display_details ( ) ;

};
In this example, an array of size 5 is declared as data member of the class to record the marks of the
student in 5 subjects. Similarly you can declare more classes having array as data member.

Check your progress/ Self assessment questions- 2

Q6. You can declare class members inside the class declaration using two access specifiers called
and .

Q7. What is the objective of private and public access specifier in a class.

Q8. You cannot create array within the declaration of class. ( TRUE / FALSE )

4.6 Data hiding and encapsulation

A program written in C++ programming language consists of the following two fundamental
components:

Page 43 of 223
1. Member functions- It is this part of the class that perform the set operations. It consists of a
set of executable statement also known as code.

2. Data Member: It is a collection of variables of objects contained in the class. These data
members are manipulated using the class member functions.

C++ provides it's programmers with a key Object Oriented Programming feature called
encapsulation that binds the data and functions together. Data encapsulation result into
another important concept called data hiding by keeping both the data and functions safe
from outside interference.

Another key feature of Object Oriented programming called data abstraction is resulted
from encapsulation. Data abstraction feature of C++ only exposes the interfaces and hide the
implementation details from the user.

C++ supports the features of encapsulation, data hiding and data abstraction with the help of
newly introduced user-defined type called class.

As already stated, use of private access specifier helps to implement the concept of data hiding. No
such restriction could be imposed in structural languages like C. Consider the following declaration
of class:
class item

{
private: int
code ; float
price ;
public:
void getdata ( ) ;
void showdata ( ) ;

};

Figure 3.1 Data hiding and encapsulation using classes

Page 44 of 223
The class prototyped consists of both the data members and member functions. It consists of 2 data
members and 2 member functions that are used to modify the data. Hence, by declaring this class type
you are able to implement the concept of encapsulation by bundling both the data and function in one
type. Member functions of the class are declared as public and hence can be accessed from both inside
and outside the class as you can see in the figure above. Both the member functions can be accessed
by any function which is outside the scope of the class and also they both can access each other from
inside the class. Data members of the class are declared as private and hence cannot be accessed by
any function from outside the class. Also the user can call the member functions to modify the content
of data members, but cannot see into the details of the member functions.

4.7 Difference between structure and class


Structure is also a user defined data type in C++ and it has already been discussed earlier in this SLM.

Class Structure
1. By default all members of a class are private 1. By default all members of a structure are
members (cannot be accesses outside class). public members ( can be accessed outside the
structure ).
2. Declared using "class" keyword. 2. Declared using "struct" keyword.
3. A special pointer called "this" works with class 3. "this" pointer does not work with structure.
type. "This" pointer refers to an object of the
same class that places a call to its member
function.
4. Class is a reference type. 4. Structure is a value type.
5. class members for objects can be initialized 5. Structure members for objects can be
using constructors. initialized without the use of constructor
function.

Check your progress/ Self assessment questions- 3

Q9. Define encapsulation.

Q10. Define data abstraction.

Q11. Use of access specifier helps to implement the concept of data hiding

Page 45 of 223
Q12. Write any 2 differences between structures and classes in C++.

4.8 Summary
A structure in C programming language is collection of heterogeneous data elements. In C
programming you cannot operate on objects of structure like you can operate on variables of default
data type. C programming does not put any restriction on the access of its members. Class is a user
defined data type which is a collection of data members and member functions. Data members and
member functions collectively are also referred to as class members. A class consists of class
declaration or class member list and class member function definitions. A class is declared using the
keyword class. In class declaration, class keyword is then followed by the name of the class that acts
as newly created abstract data type. It is then followed by the body of the class or the member list.
When you declare a class, a new abstract data type is created and you can use it just like any default
data type. Prototyping a class only creates a new abstract data type. You need to create instance of the
same to make use of it. You can create instance of a class by declaring an object of the same.You can
also declare multiple objects of a class which than creates multiple instances of the data members of
class. "This" pointer refers to an object that calls the member function of the class.
You can declare class members inside the class declaration using two access specifiers called private
and public. Class members declared as private cannot be accessed from outside the class. Whereas
class members declared as public can be accessed from both inside and outside the class. Generally
the data members are declared as private and member functions are declared as public. Data members
are hidden from outside the class. They can only be accessed from the member functions of the class.
C++ lets you create array within the declaration of class. It means that you can declare an array as
data member of class. It means you can create a data member of derived type as class member.
C++ provides its programmers with a key Object Oriented Programming feature called encapsulation
that binds the data and functions together. Data abstraction feature of C++ only exposes the interfaces
and hiding the implementation details from the user. Use of private access specifier helps to
implement the concept of data hiding that restricts access to members of class.

4.9 Glossary
Class- It is a user defined data type. A class refers to binding of data members and member functions
into one type.
Structure- It is a user defined data type. A structure refers to collection of heterogeneous data
elements into one type.
Array- It is a derived data type. It is a collection of homogeneous data elements stored contiguously in
memory.
Encapsulation- It refers to Binding of data and functions (code) in one type.
Data hiding- Data hiding is implemented in C++ with the help of private access specifier. Data hiding
refers to restricting the access of members of class.
Data abstraction- Feature of OOPs that exposes the interfaces and hides the implementation details
from the user.
Private- Class members declared as private cannot be accessed from outside the class.
Public- Class members declared as public can be accessed from outside the class.

4.10 Answers to check your progress/self assessment questions

Page 46 of 223
1. default.
2. access.
3. Class is a user defined data type which is a collection of data members and member functions.
4. abstract.
5. This.
6. private , public.
7. Class members declared as private cannot be accessed from outside the class. Their scope is limited
only to the class body, whereas class members declared as public can be accessed from both inside
and outside the class.
8. FALSE
9. Encapsulation is a key Object Oriented Programming feature that binds the data and functions
together in a single type.
10. Data abstraction feature of C++ only exposes the interfaces, hiding the implementation details
from the user.
11. private.
12.
a. By default all members of a class are private members and all members of a structure are public
members.
b. Class is a reference type and structure is a value type.

4.11 References/ Suggested Readings


1. Balagurusamy, Object Oriented Programming with C++, 3rd Edition, Tata McGraw-Hill
Education, 2006.
2. Lafore R, Object Oriented Programming in C++, 4th Edition Waite Group, 2002.
3. R. S. Salaria, Mastering Object-Oriented Programming with C++, Salaria Publishing House.

4.12 Model questions


1. Differentiate between class and structures in C++.
2. Explain the purpose of two access specifiers used in classes.
3. Explain the declaration of a class with the help of an example.
4. What do you mean by data abstraction and encapsulation.

Page 47 of 223
Lesson- 5 Definition of member functions
Structure
5.0 Objective
5.1 Introduction
5.2 Defining a member function
5.2.1 Defining member function inside the class
5.2.2 Defining member function outside the class
5.2.2.1 Inline functions
5.2.2.2 Abstraction
5.3 Private and public member functions
5.4 Nesting of member functions
5.5 Summary
5.6 Glossary
5.7 Answers to check your progress/self assessment questions

Page 48 of 223
5.8 References/ Suggested Readings
5.9 Model questions

5.0 Objective
After studying this lesson, students will be able to:
1. Define member functions inside the class.
2. Define member functions outside the class.
3. Explain the concept of inline functions.
4. State the concept of abstraction using definition of member functions outside the class.
5. Describe the nesting of member functions.

5.1 Introduction
Member functions are important component of a class. Generally we do not allow direct access to data
members of the class and they can only be accessed using the member functions of the class. In this
lesson you will learn two techniques used to define the member functions of the class. One technique
is to define the member functions of the class inside the body of the class and other is to define the
member functions outside the body the class. The later technique helps you to achieve the objective of
abstraction in object oriented programming. In this lesson you will also learn the concept of creating
nested member functions.

5.2 Defining a member function


Definition of a function includes the function header and the function body. Two methods are used to
define the member functions of a class.
 Defining member function inside the class
 Defining member function outside the class
The second method is highly recommended as it helps to achieve abstraction.

5.2.1 Defining member function inside the class


In this simple method, the definition of the member function is included within the class body. It is
inelegant method of defining a member function as it increases the length of the class member list and
also makes the class look more complicated than it is. Following is an example of a program showing
the definition of member function inside the class.

// defining member function of a class inside the member list or body of the class
# include < iostream.h >
# include < conio.h >

Page 49 of 223
class rectangle
{

private:
int length , breadth , area ;
public:
void input ( )
{
cout<<" \n Enter length of the rectangle :- " ;
cin>>length ;
cout<<" \n Enter breadth of the rectangle :- " ;
cin>>breadth ;
}
void compute_area ( )
{
area = length * breadth ;
}
void display ( )
{
cout<<" \n Area of rectangle :- " << area ;
}
};

As you can see in the code above, all three member function of the class rectangle are defined within
the body of the class. It eventually extends the length of the class.

Check your progress/ Self assessment questions- 1

Q1. List the two methods of defining the member functions of class?

Q2. Defining member functions inside the class body the length of the class
member list.

Page 50 of 223
Q3. Generally we do not allow access to data members of the class and they can only
be accessed using the of the class.

5.2.2 Defining member function outside the class

Defining the member function outside the class is the right approach to follow. It helps reduce the size
of the class and makes the class structure easy to understand. Only the declarations of the member
functions and data members are included in the class body. Following is the conversion of last
program which showed the definition of member functions inside the class to definition of member
functions outside the class.

// defining member function of class outside the member list or body of the class
# include < iostream.h >
# include < conio.h >
class rectangle
{
private:
int length , breadth , area ;
public:
// prototypes of member functions
void input ( ) ;
void compute_area ( ) ;
void display ( ) ;
};
// definition of member functions of class rectangle
void rectangle::input ( )
{
cout<< " \n Enter length of the rectangle :- " ;
cin>>length ;
cout<< " \n Enter breadth of the rectangle :- " ;
cin>>breadth ;
}
void rectangle::compute_area ( )
{
area = length * breadth ;
}
void rectangle::display ( )

Page 51 of 223
{
cout<<" \n Area of rectangle :- " << area ;
}
There are two major changes in this piece of code as compared to the code before it. Because the
member functions are defined outside the class, prototypes or declarations of the same have been
given inside the class body using the following statements:
// prototypes of member functions
void input ( ) ;
void compute_area ( ) ;
void display ( ) ;
These statements are used to indicate that these 3 are member functions of the class. Without these 3
statements, the definition of these 3 member functions outside the class would have no meaning.
Second major change is in the function header of the function definition of all the three member
functions. Consider the following definition of one member function:
void rectangle::input ( )
{
cout<< " \n Enter length of the rectangle :- " ;
cin>>length ;
cout<< " \n Enter breadth of the rectangle :- " ;
cin>>breadth ;
}

The function header contains a scope resolution operator. Scope resolution operator is used when you
define the member function outside the class. It is used to indicate that the member function belongs
to which class. For example, following function header indicates that the member function belongs to
class rectangle.
void rectangle::input ( )
It is particularly useful when the program consists of two classes having the same member functions.
Consider the following program with two classes and member functions of both the classes are
defined outside the class.

// defining member function of 2 classes outside the member list or body of the class
# include < iostream.h >
# include < conio.h >
class rectangle
{
private:

Page 52 of 223
int length , breadth , area ;
public:
//prototypes of member functions
void input ( ) ;
void compute_area ( ) ;
void display ( ) ;
};
class square
{
private:
int length , area ;
public:
// prototypes of member functions
void input();
void compute_area ( ) ;
void display ( ) ;
};
// definition of member functions of class rectangle
void rectangle::input ( )
{
cout<< " \n Enter length of the rectangle :- " ;
cin>>length ;
cout<< " \n Enter breadth of the rectangle :- " ;
cin>>breadth ;
}
void rectangle::compute_area ( )
{
area = length * breadth ;
}
void rectangle::display ( )
{
cout<< " \n Area of rectangle :- " << area ;
}
// definition of member functions of class square
void square::input ( )
{
cout<< " \n Enter length of the square :- " ;

Page 53 of 223
cin>>length ;
}
void square::compute_area ( )
{
area = length * length ;
}
void square::display ( )
{
cout<< " \n Area of square :- " << area ;
}
This is a very interesting piece of code. It consists of 2 classes having 3 member functions each. Also
the member functions of two classes have same prototypes. Here the scope resolution operator along
with function header becomes clearer. Consider the following 2 function definitions:
void rectangle::display ( )
{
cout<< " \n Area of rectangle :- " << area ;
}
void square::display ( )
{
cout<< " \n Area of square :- " << area ;
}

It is clear from the function header of the first function definition that it belongs to class rectangle and
other function definition belongs to class square.

Check your progress/ Self assessment questions- 2

Q4. Defining member function the class helps reduce the size of the class and makes the
class structure easy to .

Q5. When you define the member functions outside the class, only the of the
member functions and data members are included in the class body

5.2.2.1 Inline functions


Primary objective of creating a function is to reduce the coding effort. If a piece of code is repeated a
number of times in the program, it is better that the same is written using a separate function. The

Page 54 of 223
actual piece of code is then replaced by the function call statements where function helps in reducing
the coding effort, it makes the execution of the program slower. There is a lot of changes in the
registers when you jump between functions and also argument passing makes it even slower.
C++ provides a feature called inline function that helps solve this problem. You can make any
function an inline function by including the keyword inline in the function header as shown below:
inline Return_Type Function_name ( Argument_List )
{
// function body
}
Inline keyword is used to inform the compiler that it is an inline function. Inline function is basically
an optimization technique used by various compilers to speed up the execution of the program. By
making a function an inline function, the compiler is instructed to replace the function call statements
with the actual body of the function when making .obj file from the source file. By doing so, the
compiler saves the execution time needed to switch or jump between functions and improving the
performance. Hence as a programmer, you are able to reduce the code and also making it inline you
do not compromise on the execution time of the program.

Some of the advantages of using inline functions


1. There is no jumping between the functions and hence the overload of function calling is reduced.
2. As there is no function calling in case of inline functions, time and space is saved to maintain stack
and perform PUSH and POP operations during function calls.
3. No changes are made to the source code and hence you are able to enjoy the benefits of using
functions as such.
4. Making a function inline gives the compiler an opportunity to apply additional optimizations on the
code.

You can also make the member functions of a class that are defined outside the class to be inline
functions. A member function defined outside the class can be made inline by adding keyword inline
in front of the function header.
Example of making a member function inline.
inline ACTIVE::display ( )
{
// function body
}
Display is a member function of class ACTIVE which has been defined outside the class.
An inline member function of a class defined outside the class is same as defining the member
function within the member list or body of the class.

Page 55 of 223
When you define a member function outside the member list of the class, you cannot place a function
call statement before the definition of the same function. It can be overcome by placing the keyword
inline before the definition of the member function outside the class.

5.2.2.2 Abstraction
It is always a good programming practice to define the member functions of class outside the member
list or body of the class. When you define a member function inside the member list of the class, it
badly hurts the readability and presentation of the class. Class should only contain the prototypes of
all its members and avoid definition of any member function inside the member list of the class.
Avoiding un-necessary detailing inside the member list of the class leads to achieving Object Oriented
Programming feature of abstraction.

Check your progress/ Self assessment questions- 3

Q6. What is the impact of using functions on execution speed of program?

Q7. What is an inline function?

Q8. What is the advantage of making a function an inline function?

5.3 Private and public member functions


Normally all member functions are declared using the public access specifier. C++ allows access to
all member functions of the class declared using public specifier. But there are times when you don’t
want to give direct access to member function of class. Such a member function is created using
private access specifier. Why to create a member function which cannot be called?

5.4 Nesting of member functions

Page 56 of 223
Answer to the question in the previous section is that you create a private member function so that it
can be called or accessed using some other public member function only. It is achieved by placing a
call to the private member function inside the definition of the public member function. Hence when
you call the public member function, an automatic call is also sent to the private member function
through public member function. The concept of placing a function call statement to a member
function inside the definition of another member function is called nesting of member functions.

// demonstrating the concept of nested functions.


# include < iostream.h >
# include < conio.h >
class student
{
private:
int roll_no ;
int math ;
int science ;
int english ;
int avg ;
void average ( )
{
avg = ( math + science + english ) / 3 ;
}
public:
void inputdata ( )
{
cout<< " \n Enter roll no :- " ;
cin>> roll_no ;
cout<<" \n Enter marks in math :- " ;
cin>> math ;
cout<<" \n Enter marks in science :- " ;
cin>> science ;
cout<<" \n Enter marks in english :- " ;
cin>> english ;
}
void displayaverage ( )
{
// call to member function average ( )

Page 57 of 223
average ( ) ;
cout<< " \n Average marks :- " << avg ;
}
};
In the last piece of code, average ( ) has been defined using the private access specifier and hence
cannot be accessed directly from outside the class. Look at the following definition of member
function from the code:
void displayaverage ( )
{
average ( ) ;
cout<<" \n Average marks :- " << avg ;
}

In this piece of code, the first line in the function body is a function call statement. It is used to call
the member function defined using private access specifier. A call to function average ( ) is
automatically placed when a function displayaverage ( ) is called. Hence the average is computed first
and then the same is displayed.

Check your progress/ Self assessment questions- 4

Q9. You create a private member function so that it can be called or accessed using a
of the same class.

Q10. What do you mean by nesting of member function?

5.5 Summary
Defining member function inside the class is a simple method in which the definition of the member
function is included within the class body. Defining the member function outside the class is the right
approach to follow. It helps reduce the size of the class and makes the class structure easy to
understand. Only the declarations of the member functions and data members are included in the class
body.
Primary objective of creating a function is to reduce the coding effort. If a piece of code is repeated a
number of times in the program, it is better that the same is written using a separate function. The
actual piece of code is then replaced by the function call statements which helps in reducing the
coding effort and makes the execution of the program slower. There is a lot of changes in the

Page 58 of 223
registers when you jump between functions and also argument passing makes it even more slow. To
overcome this problem, you can make any function an inline function. Inline function is basically an
optimization technique used by various compilers to speed up the execution of the program. By
making a function an inline function, the compiler is instructed to replace the function call statements
with the actual body of the function when making .obj file from the source file. By doing so, the
compiler saves the execution time needed to switch or jump between functions and improving the
performance.
You can also make the member functions of a class that are defined outside the class to be inline
functions. An inline member function of a class defined outside the class is same as defining the
member function within the member list or body of the class. When you define a member function
outside the member list of the class, you cannot place a function call statement before the definition of
the same function. It can be overcome by placing the keyword inline before the definition of the
member function outside the class.
Sometimes you don’t want to give direct access to member function of class and such member
functions are created using private access specifier. Private member function can be called or accessed
using some other public member function only. It is achieved by placing a call to the private member
function inside the definition of the public member function. The concept of placing a function call
statement to a member function inside the definition of another member function is called nesting of
member functions.

5.6 Glossary
Inline function- Inline function tells the compiler to replace the function call statements with the
actual body of the function during compilation process.
Compiler- It is a software used to convert the source code written using some high level language into
computer understandable code (object code).
Nested member function- A private member function that is invoked using a call statement placed in
the definition of another member function.

5.7 Answers to check your progress/self assessment questions


1. Two methods used to define the member functions of a class are as follows:
a. Defining member function inside the class
b. Defining member function outside the class
2. Increases.
3. Direct , member functions.
4. Outside , understand.
5. Declarations.

Page 59 of 223
6. Where function helps in reducing the coding effort, it makes the execution of the program slower.
There is a lot of changes in the registers when you jump between functions and also argument passing
makes it even slower.
7. Inline function is an optimization technique used by various compilers to speed up the execution of
the program. By making a function an inline function, the compiler is instructed to replace the
function call statements with the actual body of the function during compilation process.
8. Making a function inline function saves the execution time needed to switch or jump between
functions and improving the performance. Hence as a programmer, you are able to reduce the code
and also making it inline you do not compromise on the execution time of the program.
9. Public member function.
10. The concept of placing a function call statement to a member function inside the definition of
another member function is called nesting of member functions.

5.8 References/ Suggested Readings


1. Balagurusamy, Object Oriented Programming with C++, 3rd Edition, Tata McGraw-Hill
Education, 2006.
2. Lafore R, Object Oriented Programming in C++, 4th Edition Waite Group, 2002.
3. R. S. Salaria, Mastering Object-Oriented Programming with C++, Salaria Publishing House.

5.9 Model questions


1. Why we declare some member functions using private access specifier.
2. What is an inline function?
3. What is the advantage of making a member function defined outside the class an inline function?
4. Write the code to define member functions of a class outside the class body.

Page 60 of 223
Lesson- 6 Class Objects
Structure
6.0 Objective
6.1 Introduction
6.2 Creating Object
6.3 Accessing class members using objects
6.4 Array of objects
6.5 Pointer to objects
6.6 Passing object as function argument
6.6.1 Pass by value
6.6.2 Pass by reference
6.7 Summary
6.8 Glossary
6.9 Answers to check your progress/self assessment questions
6.10 References/ Suggested Readings
6.11 Model questions

6.0 Objective
After studying this lesson, students will be able to:
1. Create objects of class type.
2. Access members of class using class objects.
3.Create array of class object.
4. Assign pointer to class object.
5. Pass class object as argument to a function.
6.1 Introduction
Class is a user-defined data type just like a structure, union. In order to make use of class, you need to
create objects of the same. The concept of objects is discussed in detail in this lesson. You will learn
the purpose of creating objects of a class and how are objects used in C++ programming language.
Also you will learn advanced concepts like creating array of objects and using a pointer to point an
object. Implementations are also given to help you get a better understanding of the topic. You are
already familiar with the concept of function and in this lesson you will learn how to pass object of a
class as argument to a function.
6.2 Creating Object
Class is simply a user defined data type. You have to create objects of the same to make use of it.
Object is known as the instance of the class. It is only when you create the first object of the class, that
the data members and member functions of the class are defined. In short memory is allocated to each
member of the class. When you create a class, no memory is allocated to any of its member.
You can create objects of the class just like you create objects of the structure data type.
Syntax to create object of a class

Page 61 of 223
Class_Name Object_List;
For example,
student s1, s2;
The last statement is used to create two objects of the class student.
You can also create the objects of a class using the following approach
class Class_Name
{
// class member list
} Object_List ;
For example,
class student

Page 62 of 223
{
// class member list
} s1, s2 ;
The last example is also used to create two objects of the student class.
6.3 Accessing class members using objects
Accessing the data members and member functions of the class is interesting. You cannot access all
members of the class from outside the class. You can only access the data members and member
functions of the class that are declared using the public access specifier. Members created using the
private access specifiers cannot be accessed outside the class. Before you understand the concept of
accessing the class members using the object of a class, it is important that you understand the
memory allocation for each object of the class.

Figure 6.1 Class structure and its memory allocation scheme

The figure above show the structure of a class and memory allocated to each instance or object of the
class. The student class consists of 5 data members and 3 member functions in total. Only a single
copy of all member functions is created in memory that is shared among all objects of the class. But
individual copy of data members is allocated to all objects of the class which is private to the object.
You can access data member and member function of a class using objects of the same class with the
help of dot or membership operator. Membership operator is used to specify as to which copy of data
members is to be used.
Syntax to access data member
Class_Name.Data_Member ;
Syntax to access member function
Class_Name.Member_Function ( ) ;

Program 1
Simple program to create objects of a class and access the members of the class
//header files
#include <iostream.h>

Page 63 of 223
#include<conio.h>
//definition of class
class add
{
private:
int var1;
int var2;
public:
void input ( )
{
cout<< “\nEnter value for data member var1 :- “;
cin>>var1;
cout<<”\nEnter value for data member var2 :- “;
cin>>var2;
}

void display( )
{
cout<<”\n sum of “<<var1<<” and “<<var2<<” is :- “<<var1 + var2 ;
}
};
void main( )
{
// objects of class add
add obj1, obj2;
//call to member function of obj1
cout<<"\nObject 1";
obj1.input( );
// call to member function of obj2
cout<<"\nObject 2";
obj2.input( );
// call to member function of obj1
cout<<"\nObject 1";
obj1.display();
// call to member function of obj2
cout<<"\nObject 2";
obj2.display();

Page 64 of 223
getch();
}

Two object are created in the last program for the class “add” using the following statement:
// objects of class add
add obj1, obj2;
once the objects are created the member functions for the two objects are accessed repeatedly.
Observe that the member functions input ( ) and display ( ) are accessed using obj1 and obj2 each
respectively.
obj1.input( );
obj2.input( );
The first statement is used to accept input for the data members of obj1 and the second statement is
used to accept input for the data members of obj2. Making changes to the data members of obj2 will
have no impact on the value of data members of obj1 as the copy of data members for the two objects
is different.

Output:
Object 1
Enter value for data member var1 :- 1
Enter value for data member var1 :-7
Object 2
Enter value for data member var1 :- 12
Enter value for data member var1 :-20
Object 1
Value of data member var1 :- 1
Value of data member var2 :- 7
Object 2
Value of data member var1 :- 12
Value of data member var2 :- 20

Check your progress/ Self assessment questions- 1

Q1. Object is known as the of the class.

Q2. The _and of the class are defined when the first
object of the class id declared.

Page 65 of 223
Q3. You can only access the data members and member functions of the class that are declared using
the access specifier.

Q4. Explain the concept of memory allocation to member functions and data members of a class.

Q5. You can access data member and member function of a class using of the same class
with the help of operator.

6.4 Array of objects


Just like an array of default data types, you can also create an array of objects of a class. It is
particularly useful when you wish to create large number of objects of the class. For example, array of
objects for the employee class or student class.
Syntax to create array of objects:
Class_Name Object_Name[size] ;
For example,
class student obj[3];
The last statement is used to create an array of 3 objects of student class. Just like 3 different objects
with different identifier names, the 3 members of the object array will also have a different and
private copy of data members.
You can access the member function of the class using an element of object array as follows:
Object_Name[Index].Member_Function ( );

Program 2
To create an array of class objects
// header files
#include<conio.h>
#include<iostream.h>

// definition of class student


class student
{
private:
int roll_no;
int class_no;

Page 66 of 223
int marks;
public:
void input_details ( )
{
cout<<"Enter the students class :- ";
cin>>class_no;
cout<<"Enter the students roll number:- ";
cin>>roll_no;
cout<<"Enter the students marks :- ";
cin>>marks;
}
void display_details ( )
{
cout<<"\nStudents class:- "<<class_no;
cout<<"\nStudents Roll number:- "<<roll_no;
cout<<"\nStudents marks :- "<<marks;
}
};
void main ()
{
// array of objects of student class
student obj[2];
int a;
for (a=0; a<=2;a++)
{
cout<< “ \n Enter details of student no. “<< a + 1;
obj[a].input_details( );
}
for (a=0; a<=2;a++)
{
cout<< “ \n Details of student no. “<< a + 1;
obj[a].display_details( );
}
getch();
}

Following statement is used in the last program to create an array of 2 objects for the “student” class:

Page 67 of 223
// array of objects of student class
student obj[2];
For loop is used to access each object of the array and one of the member function is accessed using
the following statement:
obj[a].input_details( );

Output:
Enter details of student no. 1
Enter the students class :- 11
Enter the students roll number:- 1
Enter the students marks :- 90
Enter details of student no. 2
Enter the students class :- 11
Enter the students roll number:- 2
Enter the students marks :- 92
Details of student no. 1
Students class:- 11
Students Roll number:- 1
Students marks :- 90
Details of student no. 2
Students class:- 11
Students Roll number:- 2
Students marks :- 92

6.5 Pointer to objects


C++ lets you create pointer of class data type. Pointer of class type can be used to refer to an object of
the same class type. All operations can be performed on pointer of class type which are possible on
pointer of any default data type. You can create a pointer of class type as follows:
Class_Name * Pointer_Name ;
This pointer can then be used to assign the address of any object of the same class.
Class_Name * Pointer_Name, Object_Name ;
Pointer_Name = & Object_Name;
The pointer object can then be used to access the member function of the class. Two methods can be
used to access members of class using pointer object.
First method is to use the "->" operator instead of "." operator.
For example,
Pointer_Name->Member_Function ( );

Page 68 of 223
Second method is to use the de-reference operator "*" along with the "." operator.
(* Pointer_Name ).Member_Function ( );

Program 3
Program to find factorial of given number using pointer to class object
//header files
#include <iostream.h>
#include<conio.h>
//definition of class
class factorial
{
private:
int var1 ;
int answer ;
public:
void setvalue ( int a )
{
var1 = a ;
answer = 1 ;
}
void compute ( )
{
int a ;
for ( a = 1 ; a < = var1 ; a++ )
answer = answer * a ;
}
void display( )
{
cout<<”\n Factorial of “<<var1<<” is “<< answer ;
}
};
void main( )
{
// object of class factorial
factorial obj1 ;
factorial *ptr_obj ;
ptr_obj = &obj1 ;

Page 69 of 223
int num ;
cout<< “\nEnter any number :- “ ;
cin>>num ;
//call to member functions of obj1
ptr_obj->setvalue( num ) ;
ptr_obj->compute( ) ;
( *ptr_obj).display ( ) ;
getch();
}

Output:
Enter any number :- 5
Factorial of 5 is 120

Check your progress/ Self assessment questions- 2


Q6. Creating array of class objects is particularly useful when you wish to create
number of objects of the class.

Q7. Pointer of type can be used to refer to an object of the same class type.

Q8. Not All operations can be performed on pointer of class type which are possible on pointer of any
default data type. (TRUE / FALSE )

Q9. How can you access members of a class using pointer object?

6.6 Passing object as function argument


C++ also allows you to pass object of a class as argument to any function. The data type of the object
as argument is the class name it belongs to. Two techniques are used to pass object of a class as
argument to a function.

6.6.1 Pass by value


Using this argument passing technique, value of actual object is passed to the formal object. The only
relationship between the actual argument and the formal argument is that they share same value. Any

Page 70 of 223
changes made to the value of formal arguments in the function definition have no impact on the value
of actual arguments passed to the function.

Program 4
Program to create swap class and passing class object using pass by value technique
//header files
#include <iostream.h>
#include<conio.h>
//definition of class
class swap
{
private:
int var1 ;
int var2 ;
public:
void setvalue ( int a , int b )
{
var1 = a ;
var2 = b ;
}
void perform ( swap obj2 )
{
obj2.var1 = obj2.var1 + obj2.var2 ;
obj2.var2 = obj2.var1 - obj2.var2 ;
obj2.var1 = obj2.var1 - obj2.var2 ;
cout<<" \n Value of var1 of formal object after swap is :- " << obj2.var1 ;
cout<<" \n Value of var2 of formal object after swap is :- " << obj2.var2 ;
}
void display ()
{
cout<<" \n Value of var1 of actual object after swap is :- " << var1 ;
cout<<" \n Value of var2 of actual object after swap is :- " << var2 ;
}

};
void main( )
{

Page 71 of 223
// object of class swap
swap obj1 ;
obj1.setvalue( 10, 20 ) ;
obj1.perform( obj1 ) ;
obj1.display ( ) ;
getch();
}
Value for both the data members var1 and var2 of obj1 are set to 10 and 20 respectively using the
following function call statement:
obj1.setvalue( 10, 20 ) ;
obj1 is then passed as argument using pass by value to perform the swap operation using the
following function call statement:
obj1.perform( obj1 ) ;
Value of actual argument obj1 passed using call by value is copied to the formal argument obj2.
void perform ( swap obj2 )
The swap operation is performed on obj2 and it has no impact on the value of data members of
obj1.
Output:
Value of var1 of formal object after swap is :- 20
Value of var2 of formal object after swap is :- 10
Value of var1 of actual object after swap is :- 10
Value of var2 of actual object after swap is :- 20

6.6.2 Pass by reference


Using this argument passing technique, address of actual object is passed to the formal object. The
relationship between the actual argument and the formal argument is that the formal argument is a
pointer variable that refers to the actual arguments. Any changes made to the value of formal
arguments in the function definition are also reflected in the actual arguments passed to the function.

Program 5
Program to create swap class and passing class object using pass by reference technique
//header files
#include <iostream.h>
#include<conio.h>
//definition of class
class swap
{

Page 72 of 223
private:
int var1 ;
int var2 ;
public:
void setvalue ( int a , int b )
{
var1 = a ;
var2 = b ;
}
void perform ( swap * obj2 )
{
obj2->var1 = obj2->var1 + obj2->var2 ;
obj2->var2 = obj2->var1 - obj2->var2 ;
obj2->var1 = obj2->var1 - obj2->var2 ;
cout<<" \n Value of var1 of formal object after swap is :- " << obj2->var1 ;
cout<<" \n Value of var2 of formal object after swap is :- " << obj2->var2 ;
}
void display ()
{
cout<<" \n Value of var1 of actual object after swap is :- " << var1 ;
cout<<" \n Value of var2 of actual object after swap is :- " << var2 ;
}

};
void main( )
{
// object of class swap
swap obj1 ;
obj1.setvalue( 10, 20 ) ;
obj1.perform( & obj1 ) ;
obj1.display ( ) ;
getch();
}
In this program, the obj1 is passed as argument using call by reference method. The address of obj1 is
passed as argument using the following statement:
obj1.perform( & obj1 ) ;

Page 73 of 223
Pointer variable is used as formal argument to copy the address of obj1 which is passed as actual
argument.
void perform ( swap * obj2 )
In this case, formal argument is a pointer variable that refers to the actual arguments. Hence any
changes made to the data members using the de-reference operator on obj2 will be reflected in obj1 as
well.

Output:
Value of var1 of formal object after swap is :- 20
Value of var2 of formal object after swap is :- 10
Value of var1 of actual object after swap is :- 20
Value of var2 of actual object after swap is :- 10

Check your progress/ Self assessment questions- 4


Q10. C++ doesn't allow you to pass object of an class as argument to any function. (TRUE / FALSE )

Q11. Explain the concept of argument passing using call by value method.

Q12. Explain the concept of argument passing using call by reference method.

6.7 Summary
Class is simply a user defined data type. You have to create objects of the same to make use of it.
Object is known as the instance of the class. It is only when you create the first object of the class, that
the data members and member functions of the class are defined. Only a single copy of all member
functions is created in memory that is shared among all objects of the class. But individual copy of
data members is allocated to all objects of the class which is private to the object. You can access data
member and member function of a class using objects of the same class with the help of dot or
membership operator. Just like an array of default data types, you can also create an array of objects
of a class.
Syntax to create array of objects:
Class_Name Object_Name[size] ;

Page 74 of 223
You can access the member function of the class using an element of object array as follows:
Object_Name[Index].Member_Function ( );
C++ lets you create pointer of class data type. Pointer of class type can be used to refer to an object of
the same class type. All operations can be performed on pointer of class type which are possible on
pointer of any default data type. Two methods can be used to access members of class using pointer
object.
First method is to use the "->" operator instead of "." operator.
Second method is to use the de-reference operator "*" along with the "." operator.
C++ also allows you to pass object of a class as argument to any function. The data type of the object
as argument is the class name it belongs to. Call by value is used to pass the value of actual argument.
The only relationship between the actual argument and the formal argument is that they share same
value. Call by reference is used to pass the address of actual argument. The relationship between the
actual argument and the formal argument is that the formal argument is a pointer variable that refers
to the actual arguments.

6.8 Glossary
Class- It is collection of data members and member functions.
Object- It is an instance of class.
Private- private members of class are not accessible outside the class.
Public- public members of class are accessible outside the class.
Array- Collection of homogeneous data elements that are stored contiguously in memory.
Pointer- It is used to store the address of another variable or reference.
Function- Block of executable statements.

6.9 Answers to check your progress/self assessment questions


1. Instance.
2. Data members , member functions.
3. Public.
4. Only a single copy of all member functions is created in memory that is shared among all objects of
the class. But individual copy of data members is allocated to all objects of the class which is private
to the object.
5. Object , dot.
6. Large.
7. Class.
8. FALSE.
9. The pointer object can then be used to access the member function of the class using following two
methods:

Page 75 of 223
First method is to use the "->" operator instead of "." operator. And the second method is to use the
de-reference operator "*" along with the "." operator.
10. FALSE.
11. Call by value is used to pass the value of actual argument. The only relationship between the
actual argument and the formal argument is that they share same value. Any changes made to the
value of formal arguments in the function definition have no impact on the value of actual arguments
passed to the function.
12. Call by reference is used to pass the address of actual argument. The relationship between the
actual argument and the formal argument is that the formal argument is a pointer variable that refers
to the actual arguments. Any changes made to the value of formal arguments in the function definition
are also reflected in the actual arguments passed to the function.

6.10 References/ Suggested Readings


1. Balagurusamy, Object Oriented Programming with C++, 3rd Edition, Tata McGraw-Hill
Education, 2006.
2. Lafore R, Object Oriented Programming in C++, 4th Edition Waite Group, 2002.
3. R. S. Salaria, Mastering Object-Oriented Programming with C++, Salaria Publishing House.

6.11 Model questions


1. Differentiate between the two methods of passing object to a function.
2. Write a program to create array of class objects.
3. Write a program to pass object to a function using call by reference.
4. Explain the memory allocation to objects of a class in detail.
5. What is a pointer. How can you use a pointer to access members of a class?

Page 76 of 223
Lesson- 7 Constructors and destructors
Structure
7.0 Objective
7.1 Introduction
7.2 Constructor
7.3 Types of constructors
7.3.1 Default constructor
7.3.2 Parameterized constructor
7.3.3 Default argument constructor
7.3.4 Copy constructor
7.4 Destructors
7.5 Differences between Constructor and Destructor
7.6 Summary
7.7 Glossary
7.8 Answers to check your progress/self assessment questions
7.9 References/ Suggested Readings
7.10 Model questions

7.0 Objective
After studying this lesson, students will be able to:

1. Define constructor and destructor


2. Explain the use of different types of constructors.
3. Differentiate between constructor and destructor.
4. Implement classes using constructor and destructor.

7.1 Introduction
So far in this SLM you have learned the concept of class and its member functions. Also you learned
how the objects of the class can be created and used to call the member functions. In this lesson you
will learn about two types of member functions of class that are automatically called when an object
of the same class is created or destroyed. Just like any other member function, you don't have to call
these two functions. These two functions have great significance and are readily used in
programming. The properties of both these functions are entirely different from simple member
functions of the class and you will learn all these properties and implementation of these two member
functions in this lesson.

7.2 Constructor
Constructor is a special member function used in C++ programming language. It is different in

Page 77 of 223
principal and implementation as compared to other member functions of a class. It is good
programming practice to have at least one constructor function in each class. Following are some of
the features of constructor function that makes it different from other member functions of class.
1. Return Type- constructor function does not have a return type and it is mandatory for any other
member function of the class. Void is also a data type and is used when the member function does not
return any value. So the constructor function does not mention any thing for the return type.
2. Name or identifier- Identifier of the member function cannot be same as identifier used for any
other type. But the name of the constructor function is same as the name of the class. For example, if
you define a class named student, the name of the constructor function will also be student.
3. Function call- In order to call a member function of a class, you need to write a function call
statement explicitly, whereas a constructor function is called automatically when the object of the

Page 78 of 223
same class is created. You can also call the constructor function by explicitly calling it using a
function call statement, but it is not mandatory.
4- Objective- Objective of the constructor function is to initialize the data members of the class. You
are not allowed to define the data members when they are declared in C++.
5. 4 Different types of constructors can be created and one class can have more than one constructor.
It is also called overloading of constructor function.

7.3 Types of constructors


In C++ you can create four types of constructors.

7.3.1 Default constructor


It is the simplest type of constructor with no arguments. Following is the syntax of default
constructor:
Class_Name ( )
Class name is also the name of the constructor function.

Program 1
To implement default constructor

//header files
#include <iostream.h>
#include<conio.h>
//definition of class
class DEFAULT
{
private:
int var1;
int var2;
public:
//default constructor
DEFAULT ( )
{
var1= 0;
var2= 0;
}
void input ( )
{

Page 79 of 223
cout<<”\nEnter value for data member var1 :- “;
cin>>var1;
cout<<”\nEnter value for data member var2 :- “;
cin>>var2;
}
void display( )
{
cout<<”\nValue of data member var1 :- “<<var1;
cout<<”\nValue of data member var2 :- “<<var2;
}
};

void main( )
{
// object of class DEFAULT
DEFAULT obj1, obj2;
//call to member function of obj2
cout<<"\nObject 2";
obj2.input( );
// call to member function of obj1
cout<<"\nObject 1";
obj1.display();
// call to member function of obj2
cout<<"\nObject 2";
obj2.display();

getch();
}

Class in the last program consists of following constructor:


//default constructor
DEFAULT ( )
{
var1= 0;
var2= 0;
}

Page 80 of 223
It is default constructor because it does not have any arguments. Also the name of the constructor is
same as the name of the class DEFAULT.

Output:
Object 2
Enter value for data member var1 :- 12
Enter value for data member var1 :- 17
Object 1
Value of data member var1 :- 0
Value of data member var2 :- 0
Object 2
Value of data member var1 :- 12
Value of data member var2 :- 17

Value for the data members of object 1 is 0 because the data members are initialized using constructor
function to 0 and no changes are made to the same.

Check your progress/ Self assessment questions- 1

Q1. Define constructor?

Q2. Constructor function does not have a .

Q3. Name of the constructor function is same as the name of the _.

Q4. Objective of the constructor function is to the data members of the class.

Q5. What is a default constructor? Also write its syntax.

7.3.2 Parameterized constructor


This is the second type of constructor that consists of arguments in the argument list. Not always you
want to initialize the data members of a class to 0 or some fix value. You may also want to allow the

Page 81 of 223
user to pass the initialization value of the data members to the constructor function. The same can be
achieved by creating a parameterized constructor and passing initialization value as arguments to the
constructor. Following is the syntax of parameterized constructor:

Class_Name (Argument_List )
Argument list may consist of one or more formal arguments.

Program 2
To implement parameterized constructor

//header files
#include <iostream.h>
#include<conio.h>
//definition of class
class PARAMETER
{
private:
int var1;
int var2;
public:
//parameterized constructor
PARAMETER ( int a, int b)
{
var1= a;
var2= b;
}
void display( )
{
cout<<”\nValue of data member var1 :- “<<var1;
cout<<”\nValue of data member var2 :- “<<var2;
}
};

void main( )
{
// object of class DEFAULT
DEFAULT obj1(13, 16), obj2 (20, 30);

Page 82 of 223
// call to member function of obj1
cout<<"\nObject 1";
obj1.display();
// call to member function of obj2
cout<<"\nObject 2";
obj2.display();

getch();
}

Class in the last program consists of following parameterized constructor:


//parameterized constructor
PARAMETER ( int a, int b)
{
var1= a;
var2= b;
}
It is parameterized constructor because it consists of two arguments. The same is called twice when
the two objects of the same class are created in function main().
DEFAULT obj1(13, 16), obj2 (20, 30);
Two actual arguments passed to the constructor function for obj1 are 13 and 16 which are assigned to
two data members of obj1 respectively.
Similarly two actual arguments passed to the constructor function for obj2 are 20 and 30 which are
assigned to two data members of obj2 respectively.

Output:
Object 1
Value of data member var1 :- 13
Value of data member var2 :- 16
Object 2
Value of data member var1 :- 20
Value of data member var2 :- 30

7.3.3 Default argument constructor


Next type of constructor also consists of arguments in the argument list. But it is different from
parameterized constructor. The default argument constructor consists of more formal arguments than

Page 83 of 223
the actual arguments that are passed to the constructor. Some of the formal arguments in the
constructor function consist of the default value.

Class_Name (Argument1, Argument2 = value )

Program 3
To implement default argument constructor

//header files
#include <iostream.h>
#include<conio.h>
//definition of class
class DEFAULT_ARGUMENT
{
private:
int var1;
int var2;
public:
//default argument constructor
DEFAULT_ARGUMENT ( int a, int b = 5)
{
var1= a;
var2= b;
}
void display( )
{
cout<<”\nValue of data member var1 :- “<<var1;
cout<<”\nValue of data member var2 :- “<<var2;
}
};

void main( )
{
// object of class DEFAULT_ARGUMENT
DEFAULT_ARGUMENT obj1(13), obj2 (20);
// call to member function of obj1
cout<<"\nObject 1";

Page 84 of 223
obj1.display();
// call to member function of obj2
cout<<"\nObject 2";
obj2.display();
getch();
}

Class in the last program consists of following default argument constructor:


//default argument constructor
DEFAULT_ARGUMENT ( int a, int b = 5)
{
var1= a;
var2= b;
}
It is called default argument constructor because it consists of two arguments and the second
argument is assigned a default value. The same is called twice when the two objects of the same class
are created in function main( ).
DEFAULT_ARGUMENT obj1(13), obj2 (20);
Only one argument 13 is passed to the constructor function for obj1 which is passed to formal
argument 'a' and another argument 'b' takes the default value of 5.
Similarly one argument 20 is passed to the constructor function for obj2 which is passed to formal
argument 'a' and another argument 'b' takes the default value of 5.
Output:
Object 1
Value of data member var1 :- 13
Value of data member var2 :- 5
Object 2
Value of data member var1 :- 20
Value of data member var2 :- 5

7.3.4 Copy constructor


Last constructor is called copy constructor. In this type of constructor reference of an object is passed
as argument to the constructor function. Copy constructor is used to initialize one object using the
reference of another object. Syntax of copy constructor is a follows:

Class_Name (Class_name &Object_Name)

Page 85 of 223
Program 4
To implement copy constructor

//header files
#include <iostream.h>
#include<conio.h>
//definition of class
class COPY
{
private:
int var1;
int var2;
public:
//default constructor
COPY ()
{
var1= 0;
var2= 0;
}
//copy constructor
COPY (COPY &obj3)
{
var1= obj3.var1;
var2= obj3.var2;
}
void input ( )
{
cout<<”\nEnter value for data member var1 :- “;
cin>>var1;
cout<<”\nEnter value for data member var2 :- “;
cin>>var2;
}
void display( )
{
cout<<”\nValue of data member var1 :- “<<var1;
cout<<”\nValue of data member var2 :- “<<var2;
}

Page 86 of 223
};

void main( )
{
// object of class COPY
COPY obj1;
// call to member function of obj1
cout<<"\nObject 1";
obj1.input();
// object of class COPY
COPYobj2(obj1);
// call to member function of obj1
cout<<"\nObject 1";
obj1.display();
// call to member function of obj2
cout<<"\nObject 2";
obj2.display();
getch();
}

Class in the last program consists of two constructor functions. One is default constructor because no
arguments are passed to the constructor function when obj1 is created.

//default constructor
COPY ()
{
var1= 0;
var2= 0;
}

For the following statement:


// object of class COPY
COPY obj1;

Second is copy constructor which is called when obj2 is created. Reference of obj1 is passed as
argument to the copy constructor.

Page 87 of 223
//copy constructor
COPY (COPY &obj3)
{
var1= obj3.var1;
var2= obj3.var2;
}
For the following statement:
// object of class COPY
COPYobj2(obj1);

Output:
Object 1
Enter value for data member var1 :- 12
Enter value for data member var1 :- 17
Object 1
Value of data member var1 :- 12
Value of data member var2 :- 17
Object 2
Value of data member var1 :- 12
Value of data member var2 :- 17

Data members of the obj2 are initialized using the obj1 and that is why the output for both the objects
is same.

Check your progress/ Self assessment questions- 2

Q6. constructor includes arguments in the argument list of function header.

Q7. The constructor consists of more formal arguments than the actual
arguments that are passed to the constructor.
Q8. What is a copy constructor?

7.4 Destructors

Page 88 of 223
Destructor is another special member function in C++ programming language. It is also automatically
called and there is no need to explicitly call it using a function call statement. Contrary to constructor
which is called automatically when the object of the same class is created, destructor is automatically
called when the object of that class is destroyed. Destructor has a great significance in C++ and it is
good programming practice to make use of the same when working with classes. Following are some
of the characteristics of destructor function in C++:
1. Automatically called: destructor function is automatically called when the object of the same class
is destroyed.
2. Single destructor- unlike construction member function, you can only have one destruction function
in a single class and there are no different types of destructors.
3. Naming- destructor naming is slightly different from construction function. It also shares the name
of the class to which it belongs to, but it is preceded by the symbol ~.
4. Objective- destruction function is mainly used to free dynamic memory allocated for the class
during run time. It is also used to decrement the counting of the objects if some variable is used to
maintain the count of objects created for the class.
5. Stack Implementation- The objects as they are created are stored in a stack data structure and if all
objects are destroyed at once, the objects are destroyed in the reverse order as stack is a last in first out
based data structure.
Syntax for defining the destructor function:
~ Class_Name ( )
{
}

Program 5
To implement the concept of destructor

//header files
#include <iostream.h>
#include<conio.h>
//definition of class
class DESTRUCTOR
{
private:
int var1;
public:
//constructor
DESTRUCTOR ( int a)

Page 89 of 223
{
var1= a;
cout<<"\nObject number "<<var1<<" is created";
}
//destructor
~ DESTRUCTOR()
{
cout<<"\nObject number "<<var1<<" is destroyed";
}
};

void main( )
{
{
// objects of class DESTRUCTOR
DESTRUCTOR obj1(1);
DESTRUCTOR obj2(2);
DESTRUCTOR obj3(3);
DESTRUCTOR obj4(4);
}
//all object destroyed
getch();
}

Class consists of a constructor function that is used to initialize or set the data member of the object to
the number of objects already created. It kinds of gives the token number to the newly created object:
DESTRUCTOR ( int a)
{
var1= a;
cout<<"\nObject number "<<var1<<" is created";
}

When all the objects are destroyed, a message is displayed to show the token number of the object
being destroyed.

Output:
Object number 1 is created

Page 90 of 223
Object number 2 is created
Object number 3 is created
Object number 4 is created
Object number 4 is destroyed
Object number 3 is destroyed
Object number 2 is destroyed
Object number 1 is destroyed

As you can observe that the objects are getting destroyed in the reverse order. i.e. the object with the
highest token number is being destroyed first.

7.5 Differences between Constructor and destructor

Constructor Destructor
1. It is automatically called when the object of the It is automatically called when the object of the
same class is created. same class is destroyed.
2. Name of the constructor function is same as Name of the destructor function is also same as
that of the class. that of the class, but it is preceded by ~ symbol.
3. You can create multiple constructor functions You can create only one destructor function for a
for a single class. single class.
4. Objective of using a constructor function is to Objective of using a destructor function is to free
initialize the data members of the class. any dynamically allocated memory during run-
time.
Check your progress/ Self assessment questions- 3

Q9. Define destructor.

Q10. You can define destruction function in a single class


Q11. is automatically called when the object of the same is class is created and
is automatically called when the object of the same is class is destroyed.
Q12. Name of the destructor function is same as that of the class, but it is preceded by ~ symbol.
(TRUE/ FALSE)

7.6 Summary

Page 91 of 223
Constructor is a special member function used in C++ programming languages. Constructor is
automatically called when the object of the same class is created. Constructor function does not have a
return type. Name of the constructor function is same as the name of the class. Constructor function is
called automatically when the object of the same class is created. You can also call the constructor
function by explicitly calling it using a function call statement, but it is not mandatory.
Objective of the constructor function is to initialize the data members of the class as you are not
allowed to define the data members when they are declared in C++. 4 different types of constructors
can be created and one class can have more than one constructor.
Default constructor does not have any argument in the argument list of the function header.
Parameterized constructor consists of arguments in the argument list. You may want to allow the user
to pass the initialization value of the data members to the constructor function. The default argument
constructor consists of more formal arguments than the actual arguments that are passed to the
constructor. Some of the formal arguments in the constructor function consists of the default value. In
case of copy constructor, reference of an object is passed as argument to the constructor function.
Copy constructor is used to initialize one object using the reference of another object.
Destructor is automatically called when the object of that class is destroyed. You can have only one
destruction function in a single class and there are no different types of destructors. . Destructor
member function shares the name of the class to which it belongs to, but it is preceded by the symbol
~. Destruction function is mainly used to free if any dynamic memory is allocated for the class during
run time. It may also be used to decrement the counting of the objects if some variable is used to
maintain the count of objects created for the class.

7.7 Glossary
Stack- It is last in first out based data structure in which the last element to be inserted is the first
element to be deleted.
Constructor - It is automatically called when the object of the same class is created.
Destructor- It is automatically called when the object of the same class is destroyed.
Class- a user defined data type that consists of data members and member functions.
Function- Block of statements to achieve a specific objective.
Object- Instance of class.

7.8 Answers to check your progress/self assessment questions

1. Constructor is a special member function of the class that is automatically called when the object of
the same class is created.
2. Return type.
3. Class

Page 92 of 223
4. initialize
5. Default constructor is one that does not have any argument in the argument list of the function
header. Following is the syntax of default constructor:
Class_Name ( ) // name of the constructor function is same as the name of the class.
6. Parameterized.
7. Default argument
8. In case of copy constructor, a reference of an object is passed as argument to the constructor
function. Copy constructor is used to initialize one object using the reference of another object.
Syntax of copy constructor is a follows:
Class_Name (Class_name &Object_Name)
9. Destructor member function is automatically called when the object of that class is destroyed.
and there is no need to explicitly call it using a function call statement.

10. one
11. Constructor, Destructor.
12. TRUE

7.9 References/ Suggested Readings


1. Balagurusamy, Object Oriented Programming with C++, 3rd Edition, Tata McGraw-Hill
Education, 2006.
2. Lafore R, Object Oriented Programming in C++, 4th Edition Waite Group, 2002.
3. R. S. Salaria, Mastering Object-Oriented Programming with C++, Salaria Publishing House.

7.10 Model questions


1. Define constructor. Why it is used in class?
2. What is a copy constructor? Write a program for the same.
3. Explain differences between constructor and destructor.
4. Explain the concept of destructor with the help of a program.
5. Explain the differences between 4 types of constructors in C++ programming language.

Page 93 of 223
Lesson- 8 Friend function and friend class
Structure
8.0 Objective
8.1 Introduction
8.2 Friend Function
8.3 Features of friend function
8.4 Implementing a friend function
8.5 Friend class
8.6 Creating a friend class
8.7Summary
8.8 Glossary
8.9 Answers to check your progress/self assessment questions
8.10 References/ Suggested Readings
8.11 Model questions

8.0 Objective
After studying this lesson, students will be able to:
1. Define the concept of friend function.
2. State features of friend function.
3. Implement the concept of friend function.
4. Define the concept of friend class.
5. Implement the concept of friend class.

8.1 Introduction
It is clear from the discussions in the earlier lessons that members declared using private access
specifier cannot be accessed from outside the class. But C++ programming language provides you
with a concept that lets you access members declared using private access specifier from outside the
class. The concept is called friend functions. In this lesson you will learn how to use friend functions
to access members declared using private access specifier from outside the class. Also you will see in
this chapter the use of friend class. You can make one class friend of another class. So my dear friend,
you are ready to enter the friendly environment of C++ programming language.

8.2 Friend Function


The concept of friend function is associated with the data hiding or encapsulation property of object
oriented programming. You already know that a class is a collection of data members and member
functions. The data members of class are generally declared under private section so that data
members cannot be accessed directly from outside the definition of class and member functions are
declared under the public section. The idea behind declaring the member functions using public
specifier is to let access members declared using private access specifier in the class, i.e. data
members through the member functions only.
C++ programming provides you with a feature that allows you to access members declared using
Page 94 of 223
private access specifier in the class from outside the class. This feature is called a friend function. The
name has been chosen very wisely. You can make any function as a friend function of any class.
What is the need of creating a friend function? Some times when you are working on a project from
onsite or from remote system (away from the actual system) and there is some problem with the
program, it is not possible to migrate the whole system or for security and other reasons it may also
not be allowed to. Then the option is to make a function friend of a class that lets you access the
insights of the actual system from outside the class. i.e. from any remote place. Without having to
copy or migrate the whole system, you are still able to access the members declared using private
access specifier in the class.

Page 95 of 223
8.3 Features of friend function
Following are some of the features of a friend function
1. Not a member function- Even though a friend function is allowed the access of members declared
using private access specifier in the class, it is not the member function of the class. It is a simple
function outside the boundaries of a class.
2. Object as argument- Class object is passed as argument to the friend function and it accesses the
members declared using private access specifier in the class using that object only. It is not
compulsory, but it is a good programming practice to do so.
3. Prototyping inside the class definition- Prototyping or declaration of the friend function is done
inside the definition of the class it is friend of. Prototyping a friend function is similar to prototyping
any other simple function except one thing and that is to add keyword friend in front of the function
prototype statement.
4. A function may be a friend of many classes- A function can be friend of any number of classes.
Simply pass object of all classes it is friend of.
5. Invoking the friend function- A friend function can be invoked or called for execution without the
use of any class object. So there is no need of the dot operator to invoke friend function.
6. No restriction of access specifier- You can declare or prototype a friend function under any access
specifier and there is no restriction on it. A friend function can be prototyped using private or public
access specifier.

Check your progress/ Self assessment questions- 1

Q1. Define friend function.

Q2. A function cannot be friend of more than one class. (TRUE/ FALSE)

Q3. A friend function can be invoked or called for execution without the use of any class object.
(TRUE/ FALSE)

8.4 Implementing a friend function

Page 96 of 223
First step in implementing a friend function is to prototype the friend function. The friend function is
prototyped inside the class definition. Friend keyword is written in front of the prototype statement to
specify that the function is simply a friend of the class.
Second step is to define the friend function. Definition of the friend function does not include the use
of the friend keyword. It is defined like any other normal function with one exception that an object is
passed as argument to the friend function. Using that object, it then accesses the private members of
the class it is friend of.

Program 1
To implement the concept of friend function
//header files
# include < iostream.h >
# include < conio.h >
//definition of class
class add

{
private:
int var1 ;
int var2 ;
//prototype of friend function
friend void plus ( add ) ;
public:
// default constructor function
add ( )

{
var1 = 0 ;
var2 = 0 ;

}
// parameterized constructor function
add ( int a , int b )

{
var1 = a ;
var2 = b ;
}

Page 97 of 223
void input ( )

{
cout<<" \n Enter value for data member var1 :- " ;
cin>>var1 ;
cout<<" \n Enter value for data member var2 :- " ;
cin>>var2 ;

void display ( )

{
cout<<" \n Value of data member var1 :- " << var1 ;
cout<<" \n Value of data member var2 :- " << var2 ;
cout<<" \n Sum of two data members is :- " << var1 + var2 ;
}
};

void main( )
{
// object of class add ;
add obj1, obj2 ( 12, 18 ) ;
//call to member function of obj1
cout<<" \n Object 1 " ;
obj1.input( );
//call to friend function
plus ( obj2 ) ;
// call to member function of obj1
cout<<" \n Object 1 " ;
obj1.display( ) ;
getch();
}

Page 98 of 223
//definition of friend function
void plus ( add obj2 )

{
obj2.var1 = obj2.var1 + 5 ;
obj2.var2 = obj2.var2 + 5 ;
// call to member function of obj2
cout<<" \nObject 2 " ;
obj2.display( );
return ;

Following statement is used in the last program to create two objects of the class add:
add obj1, obj2 ( 12, 18 ) ;
For obj1, default constructor will be called as no arguments are passed with. Both the data members
of obj1 are initialized with value 0. For obj2, parameterized constructor will be called as two
arguments are passed with it. the two data members of obj2, i.e. var1 and var2 are set to 12 and 18
respectively.
Friend function is called only once and obj2 is passed as argument to it. The values for its data
members is 12 and 18. In the definition of the friend function, values for both the data members is
incremented by 5. When you display the value of data members of obj2, 17 and 23 will be displayed.
The output for the data members of obj1 will depend on the input given by the user for them.
Output:
Object 1
Enter value for data member var1 :- 30
Enter value for data member var2 :- 40
Object 2
Value of data member var1 :- 17
Value of data member var2 :- 23
Sum of two data members is :- 40
Object 1
Value of data member var1 :- 30
Value of data member var2 :- 40
Sum of two data members is :- 70

Page 99 of 223
Now you have seen the implementation of friend function and also seen the basic features of a
friend function. A friend function of a class can be any function which is not the member function
of that class. Does it mean that a member function of one class can be a friend function of other
class? The answer is , yes. You can successfully make a member function of one class friend of
another class and directly access the private members of the second class.

Program 2
Making a member function of one class friend function of another class
// header files
# include< conio.h >
# include < iostream.h >
// prototype of class rectangle
class rectangle;
//definition of class AREA
class AREA
{
private:
int area ;
public:
AREA ( ) ;
void compute ( rectangle r2 ) ;
void display ( ) ;
};

// definition of class rectangle


class rectangle
{
private:
int length ;
int breadth ;
public:
//friend function
friend void AREA::compute ( rectangle ) ;
//constructor functions

Page 100 of 223


rectangle ( )
{
length = 0 ;
breadth = 0 ;
}
rectangle ( int a , int b )
{
length = a ;
length = b ;
}
void input ( )
{
cout<<" \n Enter the length of the rectangle :- " ;
cin>>length ;
cout<<" \n Enter the breadth of the rectangle :- " ;
cin>>breadth ;
}
};

AREA::AREA ( )
{
area = 0 ;
}
void AREA::compute ( rectangle r2 )
{
area = r2.length * r2. breadth;
}
void AREA::display ( )
{
cout<<" \n Area of rectangle is :- " << area ;
}

Page 101 of 223


void main ()
{
// object of AREA class
AREA a1;
//object of class rectangle
rectangle r1;

//accessing the member function of class rectangle


r1.input ( ) ;
//call to friend member function
a1.compute ( r1 ) ;
//call to member function of class rectangle
a1.display ( );
getch();
}
The last program starts with the prototype of rectangle class. It is so because the compute member
function of the class AREA is passes object of the class rectangle as argument. The member functions
of the class AREA are defined after the definition of class rectangle because the compute member
function of class AREA accesses the private members of class rectangle.
Output:
Enter the length of the rectangle :- 12
Enter the breadth of the rectangle :- 10
Area of rectangle is :- 120

Check your progress/ Self assessment questions- 2

Q4. It is must to prototype the friend function inside the definition of the class you want to make it
friend of. (TRUE/ FALSE)

Q5. Definition of the friend function includes the friend keyword.(TRUE/ FALSE)

Q6. Member function of one class cannot be a friend function of other class. (TRUE/ FALSE)

Page 102 of 223


You can also make a function friend of two classes. In the next program you will see how to
make a function friend function of two classes.

Program 3
Making a function friend function of two classes
// header files
# include< conio.h >
# include < iostream.h >
// prototype of class square
class square ;

// definition of class rectangle


class rectangle

{
private:
int length ;
int breadth ;
// friend function
friend void area ( square, rectangle );
public:
//constructor functions
rectangle ( )
{
length = 0 ;
breadth = 0 ;
}
rectangle ( int a , int b )
{
length = a ;
breadth = b ;

Page 103 of 223


}
};

class square
{
private:
int length ;
// friend function
friend void area ( square, rectangle );
public:
//constructor functions
square ( )
{
length = 0 ;
}
square ( int a )
{
length = a ;
}
};

void main ()
{
// object of square class
square s1 ;
//object of rectangle class
rectangle r1;
//call to friend function
area (s1, r1 );

getch ( ) ;
}

Page 104 of 223


Void area ( square s2 , rectangle r2 )
{
int areas ;
int arear ;
cout<<" \n Enter the length of the rectangle :- " ;
cin>>r2.length ;
cout<<" \n Enter the breadth of the rectangle :- " ;
cin>>r2.breadth ;
arear = r2.length * r2.breadth ;
cout<<" \n Area of rectangle is :- " << arear ;

cout<<" \n Enter the length of the square:- " ;


cin>>s2.length ;
areas = s2.length * s2.length ;
cout<<" \n Area of square is :- " << areas ;
}
Output:
Enter the length of the rectangle :- 12
Enter the breadth of the rectangle :- 10
Area of rectangle is :- 120
Enter the length of the square :- 10
Area of square is :- 100

8.5 Friend class


So far, you have learned about a friend function and how to make a function friend of two classes. In
this section, you will learn to create a friend class. Making a member function friend of some class,
you can only access the private members of one class with the definition of the friend member
function of another class. But using the concept of friend class, you can make the entire class friend of
another class and access private members of first class from anywhere within the definition of second
class.

8.6 Creating a friend class


Following is the program to make a class friend of another class:
Program 4

Page 105 of 223


Making a class friend of another class
// header files
# include< conio.h >
# include < iostream.h >
// definition of class rectangle
class rectangle

{
private:
// making a friend class
friend class AREA ;
int length ;
int breadth ;
public:
//constructor functions
rectangle ( )
{
length = 0 ;
breadth = 0 ;
}
rectangle ( int a , int b )
{
length = a ;
length = b ;
}
};
//definition of class AREA
class AREA
{
private:
int area ;
rectangle r1 ;
public:

Page 106 of 223


AREA ( ) ; void
input ( ) ; void
compute () ; void
display ( ) ;
};
Void AREA::input ( )
{
cout<<" \n Enter the length of the rectangle :- " ;
cin>>r1.length ;
cout<<" \n Enter the breadth of the rectangle :- " ;
cin>>r1.breadth ;
}
AREA::AREA ( )
{
area = 0 ;
}
void AREA::compute ()
{
area = r1.length * r1. breadth;
}
void AREA::display ( )
{
cout<<" \n Area of rectangle is :- " << area ;
}
void main ()
{
// object of AREA class
AREA a1;
//accessing the member functions of friend class AREA
a1.input ( ) ;
a1.compute ( ) ;
a1.display ( );

Page 107 of 223


getch();
}
Output:
Enter the length of the rectangle :- 12
Enter the breadth of the rectangle :- 12
Area of rectangle is :- 144

Check your progress/ Self assessment questions- 3

Q7. You can also make a function friend of two classes. (TRUE/ FALSE)

Q8. You can make one class friend of another class.(TRUE/ FALSE)

Q9. What is the difference between making a member function of one class friend of another class
and making an entire class friend of another class.

8.7 Summary
The data members of class are generally declared under private section so that data members cannot
be accessed directly from outside the definition of class and member functions are declared under the
public section. A friend function is allowed to access members declared using private access specifier
in the class from outside the class. You can make any function as a friend function of any class.
Making a function friend of a class lets you access the private members of a class only within the
definition of the class and not from anywhere outside the class. Following are some of the features of
a friend function:
1. Not a member function
2. Object as argument
3. Prototyping inside the class definition
4. Can be friend of many classes
5. Invoking the friend function
6. No restriction of access specifier
First step in implementing a friend function is to prototype the friend function. The friend function is
prototyped inside the class definition. Second step is to define the friend function. Definition of the

Page 108 of 223


friend function does not include the use of the friend keyword. It is defined like any other normal
function.
Member function of 1 class can be a friend function of other class. A function can be made friend of
more than 1 class. Object of each class it is friend of, is passed as argument to the friend function.
You can also make a class friend of another class. Using the concept of friend class, you can make the
entire class friend of another class and access the members declared using private access specifier in
first class from anywhere within the definition of second class.

8.8 Glossary
Friend function-A friend function is allowed to access members declared using private access
specifier in a class from outside the class.

Friend class-It can access the members declared using private access specifier of any class from
anywhere within its own definition.

Friend member function- Member function of 1 class allowed to access the members declared using
private access specifier in other class from within the definition of that member function.

Class- Collection or binding of data members and member functions

Object- An instance of any class.

8.9 Answers to check your progress/self assessment questions


1. A friend function in C++ is allowed to access the private members of the class from outside the
class. It is not the member function of the class and hence not under the scope of the class.
2. FALSE
3. TRUE
4. TRUE
5. FALSE
6. FALSE
7. TRUE
8. TRUE
9. By making a member function of a class friend of another class, you can only access the private
members of one class with the definition of the friend member function of another class. But using the
concept of friend class, you can make the entire class friend of another class and access the private
members of first class from anywhere within the definition of second class.

Page 109 of 223


8.10 References/ Suggested Readings

1. Balagurusamy, Object Oriented Programming with C++, 3rd Edition, Tata McGraw-Hill
Education, 2006.
2. Lafore R, Object Oriented Programming in C++, 4th Edition Waite Group, 2002.
3. R. S. Salaria, Mastering Object-Oriented Programming with C++, Salaria Publishing House.

8.11 Model questions


1. What is a friend function?
2. Explain various features of friend function in detail.
3. Write a program to implement friend function.
4. What is a friend class? Explain with the help of a program.
5. Write a program to make a function friend of three classes.

Page 110 of 223


Lesson- 9 Static members
Structure
9.0 Objective
9.1 Introduction
9.2 Static data member
9.2.1 Scope resolution operator
9.2.2 Implementing static data member
9.3 Static member functions
9.3.1 Features of static member functions
9.3.2 Implementing static member functions
9.4 Summary
9.5 Glossary
9.6 Answers to check your progress/self assessment questions
9.7 References/ Suggested Readings
9.8 Model questions

9.0 Objective
After studying this lesson, students will be able to:
1.Define the concept of static data member.
2. Implement static data member in a class.
3. Define the concept of static member function.
4. Implement static member function in a class.

9.1 Introduction
As already stated in the earlier lessons, class is a collection of data members and member functions.
When you create objects of some class, data members for each object are separate. It means for 5
objects, 5 copies of each data member are created and each copy is specific to one object. In this
lesson, you will learn about static data members which are also class data members. Static data
members are different from simple data members and are also used differently from them. You will
also learn the implementation of the same. Later in this lesson you will learn about static member
functions which are created keeping in mind the static data members only.

9.2 Static data member


Class is a collection of data members and member functions. When you create an object of a class,
copy of each data member is created for that object. When you create second object of a class,
additional copy of data members is created for the second object. Copy of data members for each
object is private to that object only and cannot be accessed by other objects.

Page 111 of 223


Consider the following class structure for example,

Figure 9.1 "student" class structure


The class "student" consists of 5 data members and 3 member functions. The memory allocated to
member functions is shared amongst all objects of the class, but separate and private copies for data
members is allocated to each object of the class. For example, consider that 3 objects of the class
"student" are created.

Page 112 of 223


Figure 9.2 Memory allocation for "student" class shown in figure 9.1
As you can see in the figure above, separate and private copy of all data members is allocated to each
class object, but a single copy of member functions is shared by all class objects.
What is static data member?
Static data member is also called class member. It is called so because only one copy of the static data
member is created irrespective of the number of objects created for the same class. It means, a static
data member is one for which only one copy is created which is shared by all objects of the class.
Consider the following structure of a class and its memory allocation in the subsequent figure:

Figure 9.3 "student" class structure with a static data member


The only difference between the structures of figure 9.1 and figure 9.3 is that the latter one includes a
static data member.

Page 113 of 223


Figure 9.4 Memory allocation for "student" class shown in figure 9.3
As you can see in the figure above, only a single copy of the static data member is created which is
shared by all objects of the class similar to member functions.

Check your progress/ Self assessment questions- 1

Q1. Class is a collection of and .

Q2. How many copies of normal data members created?

Q3. What is a static data member?

9.2.1 Scope resolution operator


The normal data members of a given class can be accessed using a dot operator with object name to
which they belong. But a static data member does not belong to any object and it belongs to the class
itself. Hence it is accessed using a scope resolution operator along with the class name. Also the
normal data members are defined when the object of that class is created. If no object is created, data
member of the class are not defined. In case of static data members, there is no connection between
the creation of class objects and definition of static data members. Even if no object of the class is

Page 114 of 223


created, the static data member can still be defined. The static data member needs to be defined
explicitly after the definition of the class.
Syntax to define the static data member:
Data_Type Class_Name:: Static_Data;
For example,
student::count;
the last statement is used to define the count of static data member of the class student. The static
data member is declared in the class using the static keyword.
Initialization
Normal data member is defined when the object of that class is created. If no constructor function is
defined for that class, the normal data members are initialized with some garbage value. But in case of
static data member, when it is explicitly defined, it is automatically initialized with value 0.
Program 1
To count the number of active objects using static data member

//header files
# include < iostream.h >
# include < conio.h >
//definition of class
class ACTIVE
{
public:
static int count ;
// constructor function
ACTIVE ( )
{
count++ ;
cout<<" \n Object number :- " << count << " created " ;
}
//destructor function
~ ACTIVE ( )
{
count -- ;
cout <<" \n Object destroyed. " ;
}
};

Page 115 of 223


//definition of static variable
int ACTIVE::count ;

void main( )
{
// object of class ACTIVE
{
ACTIVE obj1 ;
{
ACTIVE obj2 ;
{
ACTIVE obj3 ;
}
}
//accessing static data member
cout<<" \n Objects remaining :- " << ACTIVE::count ;
}
cout<<" Objects remaining :- " << ACTIVE::count ;
getch( ) ;
}
Objects in the last program are intentionally created inside blocks or curly braces. Once the block
comes to an end, the object created inside the block is destroyed and hence the destructor function of
the same is called. When an object is created, the value of the static data member is incremented by 1
using the constructor function and when the object is destroyed, the value of the static data member is
decremented by one using the destructor function. Following statement is used to access the static
member with the help of scope resolution operator to display the count of currently active objects of
the class.
cout<<"\nObjects remaining :- "<<ACTIVE::count;

Output:
Object number :- 1 created
Object number :- 2 created
Object number :- 3 created
Object destroyed.
Object destroyed.
Objects remaining :- 1
Object destroyed.

Page 116 of 223


Objects remaining :- 0

PROGRAM 2
Attendance marking using static data member

// header files
# include <conio.h>
# include <iostream.h>

// definition of class student


class student
{
private:
int roll_no, class_no, attendance ;

public:
//static data member
static int total;
//constructor function
Student ( )
{
roll_no = 0 ;
class_no = 0 ;
attendance = 0 ;
}
void input_details ( )
{
cout<<" \n Enter the students roll number:- " ;
cin>>roll_no ;
cout<<" Enter the students class :- " ;
cin>>class_no ;
}
void mark_attendance ( )
{
char temp ;

Page 117 of 223


cout<<" Is the student present: (y / n ) ? " ;
temp = getche( ) ;
if ( temp == 'y' )
{
attendance++ ;
}
}
void display_details ( )
{
cout<<" \n Students roll_no :- " << roll_no ;
cout<<" \n Students class:- " << class_no ;
cout<<" \n Students attendance :- " << attendance ;
}
};
//definition of static data member
int student::total ;
void main ( )
{
int days ;
// object of class student
student obj1 , obj2 ;
//member function called
cout<<" \n Student 1 " ;
obj1.input_details ( ) ;
cout<<" \n Student 2 " ;
obj2.input_details ( ) ;
cout<<" Number of days classes held :- " ;
cin>>days ;

//marking attendance
for ( int a = 1 ; a <= days ; a++ )
{
student::total++ ;
cout<<" \n Day :- " << student::total ;
cout<<" \n Student 1 " ;
obj1.mark_attendance( ) ;
cout<<" \n Student 2 " ;

Page 118 of 223


obj2.mark_attendance( ) ;
}
//display record
cout<<"\n Total classes held :- " << student::total ;
obj1.display_details ( ) ;
obj2.display_details ( ) ;
getch( ) ;
}
Output:
Student 1
Enter the students roll number :- 1
Enter the students class :- 11
Student 2
Enter the students roll number :- 2
Enter the students class :- 11
Number of days classes held :- 3
Day :- 1
Student 1 Is the student present: (y / n ) ? y
Student 2 Is the student present: (y / n ) ? n
Day :- 2
Student 1 Is the student present: (y / n ) ? y
Student 2 Is the student present: (y / n ) ? n
Day :- 3
Student 1 Is the student present: (y / n ) ? n
Student 2 Is the student present: (y / n ) ? y
Total classes held :- 3
Students roll_no :- 1
Students class:- 11
Students attendance :- 2
Students roll_no :- 2
Students class:- 11
Students attendance :- 1

Check your progress/ Self assessment questions- 2

Q4. The normal data members of a given class can be accessed using a operator with
name to which they belong.

Page 119 of 223


Q5. data member is accessed using a scope resolution operator along with the class
name.

Q6. What is the difference between definition of normal data member and static data member of a
class?

Q7. A normal data member is initialized with value and a static data member is
automatically initialized with value .

9.3 Static member functions


Just like a static data member, static function is also a special member function of the class. A static
member function can be prototyped with the help of the static keyword.

9.3.1 Features of static member functions


Following are the key properties of the static member function of the class:
1. Access to static Data members only- A static member function can access only the static data
members of a class. It cannot be used to access the other data members of the class. Attempting to
access normal members from within the definition of static member function will generate an error.
2. Invoking Static member function- A normal member function of the class is invoked using the
object of that class and dot or membership operator. Whereas a static member function is invoked
using the class name and the scope resolution operator.

9.3.2 Implementing static member functions


Following is the program to implement the static member function.
Program 1
To implement the concept of static member function

//header files
# include < iostream.h >
# include < conio.h >
//definition of class
class ACTIVE
{

Page 120 of 223


private:
// static data member of the class
static int count ;
public:
// constructor function
ACTIVE ( )
{
count++ ;
cout<<" \n Object number :- " << count << " created " ;
}
//destructor function
~ ACTIVE ( )
{
count -- ;
cout <<" \n Object destroyed. " ;
}
// static member function of the class
static void display ( )
{
cout<<" \n Objects remaining :- " << count ;
}
};

//definition of static variable


int ACTIVE::count ;
void main( )
{
// object of class ACTIVE
{
ACTIVE obj1 ;
{
ACTIVE obj2 ;
{
ACTIVE obj3 ;
}
}
//accessing static member function of the class

Page 121 of 223


ACTIVE::display ( ) ;
}
//accessing static member function of the class
ACTIVE::display ( ) ;
getch( ) ;
}
The last program consists of a class with a static member function:
static void display ( )
{
cout<<" \n Objects remaining :- " << count ;
}
The objective of the static member function is to display the value of the static data member. A static
data member cannot be used to access any data members of the class which are not static.
The objective of the program is same as that of the program 1 in this lesson. The static data function is
invoked using the following statement:
//accessing static member function of the class
ACTIVE::display ( ) ;
Where ACTIVE is the name of the class and display ( ) is a static function. A static member function
can be invoked with the help of the scope resolution operator as shown in the statement above.
Output:
Object number :- 1 created
Object number :- 2 created
Object number :- 3 created
Object destroyed.
Object destroyed.
Objects remaining :- 1
Object destroyed.
Objects remaining :- 0

Check your progress/ Self assessment questions- 3

Q8. Which all data members can be accessed using static member function?

Page 122 of 223


Q9. How can you invoke a static member function of a class?

9.4 Summary
Class is a collection of data members and member functions. When you create an object of a class,
copy of each data member is created for that object. When you create second object of a class,
additional copy of data members is created for the second object. Static data member is also called
class member. It is called so because only one copy of the static data member is created irrespective of
the number of objects created for the same class. It means, a static data member is one for which only
one copy in created which is shared by all objects of the class.
The normal data members of a given class can be accessed using a dot operator with object name to
which they belong. But a static data member does not belong to any object and it belongs to the class
itself. Hence it is accessed using a scope resolution operator along with the class name. The normal
data members are defined when the object of that class is created. If no object is created, data member
of the class are not defined. In case of static data members, there is no connection between the
creation of class objects and definition of static data members. The static data member needs to be
defined explicitly after the definition of the class.
Normal data member is defined when the object of that class is created. If no constructor function is
defined for that class, the normal data members are initialized with some garbage value. But in case of
static data member, when it is explicitly defined, it is automatically initialized with value 0.
Just like a static data member, static function is also a special member function of the class. A static
member function can be prototyped with the help of the static keyword. A static member function can
access only the static data members of a class. It cannot be used to access the other data members of
the class. Attempting to access normal members from within the definition of static member function
will generate an error. A normal member function of the class is invoked using the object of that class
and dot or membership operator. Whereas a static member function is invoked using the class name
and the scope resolution operator.

9.5 Glossary
Static data member- A data member for which only one copy is created irrespective of the number of
objects created for the same class.

Page 123 of 223


Static member function- A member function of the class used to access only the static data members
of the class.
Scope resolution operator- It is used to specify the scope of a data member or member function.
Class- Collection of data members and member functions.
Object- Instance of a class.
Garbage value- When a program allocates a block of memory to a variable and does not initialize it,
the memory block still contains some left over value in it from previous programs called a garbage
value. It can be avoided by initializing the variables.

9.6 Answers to check your progress/self assessment questions

1. Data members , member functions.


2. When you create an object of a class, copy of each data member is created for that object. When
you create second object of a class, additional copy of data members is created for the second object.
It means a separate copy of each data member is created for all objects.
3. Static data member is also called class member. It is called so because only one copy of the static
data member is created irrespective of the number of objects created for the same class. It means, for a
static data member only one copy in created which is shared by all objects of the class.
4. Dot , object.
5. Static
6. A normal data member is defined when the object of that class is created. If no object is created,
normal data member of the class are not defined. In case of static data members, there is no
connection between the creation of class objects and definition of static data members. The static data
member needs to be defined explicitly after the definition of the class.
7. Garbage, 0.
8. A static member function can access only the static data members of a class. It cannot be used to
access the other data members of the class. Attempting to access normal members from within the
definition of static member function will generate an error.
9. A static member function of a class can be invoked using the class name and the scope resolution
operator. for example,
ACTIVE::display ( ) ;
The statement above is used to invoke static member function display ( ) which is a member function
of class ACTIVE.

9.7 References/ Suggested Readings

Page 124 of 223


1. Balagurusamy, Object Oriented Programming with C++, 3rd Edition, Tata McGraw-Hill
Education, 2006.
2. Lafore R, Object Oriented Programming in C++, 4th Edition Waite Group, 2002.
3. R. S. Salaria, Mastering Object-Oriented Programming with C++, Salaria Publishing House.

9.8 Model questions


1. What is a static data member?
2. How can you invoke a static member function?
3. What is the default value of static data member and how it is defined in C++?
4. Write a program to implement the concept of static data member.
5. Explain the two key properties of static member function.

Page 125 of 223


Lesson- 10 Fundamentals of inheritance
Structure
10.0 Objective
10.1 Introduction
10.2 What is inheritance?
10.3 Base and derived class
10.4 Types of inheritance
10.5 Defining derived class
10.6 Summary
10.7 Glossary
10.8 Answers to check your progress/self assessment questions
10.9 References/ Suggested Readings
10.10 Model questions

10.0 Objective
After studying this lesson, students will be able to:
1. Define the concept of inheritance
2. Explain the relationship between the base and derived class.
3. Implement the definition of derived class.
4. Discuss the visibility modes in context to inheritance.
10.1 Introduction
In this lesson you will learn yet another powerful feature of C++ programming language called
inheritance. So far you have learned to create a class, create objects of the same and access the
members of the class using the object of the same class. Reusability is the key advantage of using
classes and important feature of object oriented programming. Software engineering has fast emerged
as vital subject in the field of computer science. Early efforts were focused on reducing the hardware
cost. But the increase in the cost of software was exponential. Modular programming and the ability
to re-use the existing code without much effort is the focus of today's programming. In this lesson
you will learn the fundamentals of how a class can be re-used to create a new class by inheriting the
features of the old class.
10.2 What is inheritance?
It is highly motivating when you design or code something and able to use the same again and again
in new programs without having to start from the very beginning. It helps to reduce a lot of effort and
also the money involved to develop the same code again. If you can re-use a class that has already
been successfully deployed (coded, tested, debugged), helps time of the developers by not having to
code the same when working on a new project.
C++ lets you re-use an already tested class in several ways. An already tested class can be adapted by
the programmers according to their requirement. It means you can create a new class by using or re-
Page 126 of 223
using the features of an already existing class or classes in C++. This feature of being able to derive
or create a new class from an existing class in C++ is called inheritance.

10.3 Base and derived class


Inheritance is the concept of breaking a large class into small classes and establishing the relationship
amongst those classes. Single class for a large project is undesirable and difficult to manage. It also
decreases the performance as all components of a class are not needed. C++ lets you set the
relationship between the classes and create new classes that can use the features of already existing
classes without any effort.
Terminology used for the existing class in inheritance is base class and the newly created class using
the features of base class is called derived class. Derived class may inherit all or some of the features

Page 127 of 223


of base class. Can a class inherit features from more than one class, or can a class be inherited by
more than one derived class, or can we create a chain of inheritance where a derived class can also be
inherited by another class.? Answers to all these questions, are given in the next section.
Check your progress/ Self assessment questions- 1

Q1. Reusability helps to reduce and involved to develop the code.

Q2. Define inheritance.

Q3. Define base and derived class.

10.4 Types of inheritance


Inheritance can be achieved in C++ programming language in many ways. Depending upon the
requirement, the programmer is able to set the relationship between the classes and decide the rules
for which parts of the base class can be inherited by the derived class. Real benefits of inheritance can
only be achieved if you use the right type of inheritance and right mode of inheritance. Inheritance is
based on hierarchical relationship amongst the classes. Based on the relationship topology, inheritance
in C++ can be of following types:
1. Single Inheritance: It is the most basic inheritance type. It is called single inheritance as there is
one base class from which only one class is derived. It also means that there is only a single level of
inheritance.

Page 128 of 223


Figure 10.3 Single inheritance.

Figure 10.2 Example of single inheritance.


Example of figure 10.2 shows how a class "marks" is derived from the base class "student". Input of
marks is independent of getting input of student details and hence two classes are used to represent
student information.
2. Multiple inheritance: Just like in single inheritance, multiple inheritance is also limited to single
level of inheritance only. The difference lies in the number of base classes involved. In case of
multiple inheritance, a class is derived from more than one base classes. All the base classes in
multiple inheritance are at the same level.

Figure 10.3 Multiple inheritance.

Page 129 of 223


Figure 10.3 Example of multiple inheritance
Figure 10.3 shows an example of multiple inheritance. Derived class "rectangle" is used to accept the
length and breadth of the rectangle shape. It is derived from two base classes. One is used to compute
the area of the of the rectangle and one is used to compute the perimeter of rectangle. There is a clear
separation between the two entities.
There are ambiguity problems associated with multiple inheritance. As you know that a derived class
can inherit the features of the base class. In case of multiple inheritance, there are more than one base
classes. If 2 base classes have same member functions, it gives birth to the problem of ambiguity. The
compiler is caught between the two base classes. To overcome this problem you need to bind the
member function with the specific base class using the scope resolution operator before using it.

3. Hierarchical inheritance: It is yet another inheritance with single level only. Here the difference
lies in the number of derived class involved. In case of hierarchical inheritance, multiple classes are
derived from a single base class and all derived classes are at the same level. Hierarchical inheritance
is just like a tree data structure with single level.

Figure 10.5 Hierarchical inheritance

Page 130 of 223


Figure 10.6 Example of hierarchical inheritance.
Base class area is prototyped to compute the area of various shapes. Then two classes named
"rectangle" and "square" are derived from the base class "area". After getting input for perimeters that
represent the shape, derived class used the base class to compute the area.

Check your progress/ Self assessment questions- 2

Q4. Define single inheritance.

Q5. Multiple inheritance can have multiple levels of inheritance. ( TRUE / FALSE )

Q6. Define multiple inheritance.

Page 131 of 223


Q7. Hierarchical inheritance is just like a data structure with level.
Q8. How hierarchical inheritance is different from multiple inheritance?

4. Multilevel inheritance: It is a straight forward extension of single inheritance. Multilevel


inheritance involves more than one level of inheritance. It means, that some of the derived classes are
treated as intermediate base classes that are further used to derive classes. But at any two consecutive
levels, there is one base class at one level and one derived class at next level.

Figure 10.7 multilevel inheritance

Figure 10.8 Example of multilevel inheritance.


Multilevel inheritance lets you create an intermediate base class. In this example, class "marks" is that
intermediate class. It is derived from the base class "student" and is further used for deriving the class

Page 132 of 223


"result". Student is first enrolled. After the student is enrolled, at some point after examinations
his/her marks are uploaded using the marks class. Final step is to display the result on the day of
result. It clearly shows that the operations of three classes are independent of each other and it
justifies the multilevel inheritance.
5. Hybrid inheritance: Inheritance relationship amongst the classes is much more complicated in
practical applications developed using C++ programming language than the one's listed above. Hybrid
inheritance is combination of two or more types of inheritances listed above. For a successful
implementation of hybrid inheritance you must know the features of all types of inheritances.

Figure 10.9 One possible relationship for hybrid inheritance

Figure 10.10 Example of hybrid inheritance


Hybrid example shown in figure 10.10 is a combination of multilevel inheritance and multiple
inheritance. Class "marks" acts as intermediate base class for multilevel inheritance. It is derived from
the base class "student" and class "result" is further derived from this class. Also the derived class
"result" at bottom level is inherited from one more base class "extra". Because the class "result" is
derived from two base classes, it is also an example of multiple inheritance. This example justifies the
use of hybrid inheritance. Student may or may not opt for extra class and hence it is not part of the
multilevel inheritance.
Check your progress/ Self assessment questions- 3

Page 133 of 223


Q9. Multilevel inheritance is a straight forward extension of inheritance.

Q10. Define multilevel inheritance.

Q11. Why do we need hybrid inheritance?

Q12. Define hybrid inheritance.

10.5 Defining derived class


Defining a derived class is slightly different from defining a simple class. When you define a derived
class, you also specify its relationship with the base class. The relationship is specified next to the
class name in class definition.
Syntax for defining a derived class:
Class Derived_Class_Name : Inheritance_Mode Base_Class_Name
The colon operator ":" is used to specify that the derived class being defined is derived from a specific
base class or base classes. The inheritance mode is optional and is discussed in the next lesson where
you will learn to implement the inheritance. It is important to mention that the inheritance mode is

Page 134 of 223


optional and by default it is private. It can take one of the three values; private, public and protected.
Protected keyword is also discussed in length in the next lesson.
Consider the following 2 base classes
class base1 // definition of base class
{
// members of base class base1
};
class base2 // definition of base class
{
// members of base class base2
};
A class can be derived from the base class base1 as follows:
class derived1 : base1 // defining the derived class
{
// members of the derived class derived1
};
No inheritance mode has been specified which means that the inheritance mode by default is private.
There is one base class and one derived class which means that it is an example of single inheritance.
A class can be derived from both the base classes; base1 and base2 as follows:
class derived2 : base1 , base2 // defining the derived class
{
// members of the derived class derived2
};
When you inherit a derived class from two or more base classes, names of the base classes are
separated using the comma operator and the inheritance modes for all base classes is mentioned
separately.
Deriving a class from a derived class to implement multilevel inheritance
class derived2 : derived1 // defining the derived class
{
// members of the derived class derived3
};
Class derived2 is derived from class derived1. The class derived1 is further derived from class base
which makes derived1 an intermediate class.

Check your progress/ Self assessment questions- 4

Q13. How defining a derived class is different from defining a simple class?

Page 135 of 223


Q14. What is the role of ":" colon operator in class definition?

Q15. The inheritance mode in definition of derived class is optional ( TRUE / FALSE )

Q16. Inheritance mode can take one of the three values; , and
.

Q17. is the default inheritance mode when defining a derived class.


Q18. How do you define a derived class for multiple inheritance?

10.6 Summary
Ability to use the same code again and again in new programs without having to start from the very
beginning helps to reduce a lot of effort and money involved. C++ lets you re-use an already tested
class in several ways. You can create a new class by using or re-using the features of an already
existing class or classes in C++. This feature of being able to derive or create a new class from an
existing class in C++ is called inheritance. Terminology used for the existing class in inheritance is

Page 136 of 223


base class and the newly created class using the features of base class is called derived class. Derived
class may inherit all or some of the features of base class.
Inheritance in C++ is of following types:
Single inheritance in which there is one base class from which only one class is derived and also there
is only a single level of inheritance.
Multiple inheritance is one in which a class is derived from more than one base classes. All the base
classes in multiple inheritance are at the same level.
Hierarchical inheritance is one in which multiple classes are derived from a single base class and all
derived classes are at the same level.
Multilevel inheritance is an extension of single inheritance. Some of the derived classes are treated as
intermediate base classes that are further used to derive classes.
Hybrid inheritance is combination of two or more types of inheritances.
Defining a derived class is slightly different from defining a simple class. When you define a derived
class, you also specify its relationship with the base class. The relationship is specified next to the
class name in class definition. Syntax for defining a derived class is as follows,
Class Derived_Class_Name: Inheritance_Mode Base_Class_Name
The colon operator ":" is used to specify that the derived class being defined is derived from a specific
base class or base classes. The inheritance mode is optional and private by default. It can take one of
the three values; private, public and protected.

10.7 Glossary
Reusability- Ability of a programming language to re-use the code.
Inheritance- Feature of being able to derive or create a new class from an existing class in C++ is
called inheritance
Base class- Already existing class from which a class is inherited is called base class
Derived class- Newly created class using the features of base class is called derived class.
Single inheritance- In which there is one base class from which only one class is derived and also
there is only a single level of inheritance.
Multiple inheritance- In which a class is derived from more than one base classes. All the base classes
in multiple inheritance are at the same level.
Hierarchical inheritance- In which multiple classes are derived from a single base class and all derived
classes are at the same level.
Multilevel inheritance- In which some of the derived classes are treated as intermediate base classes
that are further used to derive classes.
Hybrid inheritance- It is a combination of two or more types of inheritances.
10.8 Answers to check your progress/self assessment questions
1. effort , money.

Page 137 of 223


2. Feature of object oriented programming that lets you to derive or create a new class from an already
existing class in C++ is called inheritance. The newly created class can use the features of an already
existing class or classes in C++.
3. Already existing class from which a class is inherited is called base class and the newly created
class using the features of base class is called derived class. Derived class may inherit all or some of
the features of base class.
4. In single inheritance there is one base class from which only one class can be derived. It also means
that there is only a single level of inheritance.
5. FALSE.
6. . In case of multiple inheritance, a class is derived from more than one base classes. All the base
classes in multiple inheritance are at the same level.
7. tree , single
8. In hierarchical inheritance multiple classes can be derived from a single base class and in multiple
inheritance one class is derived from more than one base classes.
9. single.
10. Multilevel inheritance involves more than one level of inheritance. It means, that some of the
derived classes are treated as intermediate base classes that are further used to derive classes.
11. Hybrid inheritance is used because inheritance relationship amongst the classes is much more
complicated in practical applications developed using C++ programming language. These
relationships cannot be expressed using four basic inheritance types.
12. Hybrid inheritance is combination of two or more basic types of inheritances like single, multiple,
hierarchical and multilevel inheritances. For a successful implementation of hybrid inheritance, you
must know the features of all types of inheritances.
13. When you define a derived class, you also specify its relationship with the base class. No such
relationship is specified when you create a simple class. The relationship is specified next to the class
name in class definition of derived class.
14. The colon operator ":" is used to specify that the derived class being defined is derived from a
specific base class or base classes.
15. TRUE.
16. private, public , protected.
17. private.
18. In multiple inheritance, a class is derived from multiple base classes. When you inherit a derived
class from two or more base classes, names of the base classes are separated using the comma
operator and the inheritance modes for all base classes is mentioned separately.
10.9 References/ Suggested Readings
1. Balagurusamy, Object Oriented Programming with C++, 3rd Edition, Tata McGraw-Hill
Education, 2006.

Page 138 of 223


2. Lafore R, Object Oriented Programming in C++, 4th Edition Waite Group, 2002.
3. R. S. Salaria, Mastering Object-Oriented Programming with C++, Salaria Publishing House.

10.10 Model questions


1. Define inheritance and what is the importance of inheritance?
2. Define base and derived classes.
3. What is the difference between multiple and hierarchical inheritances?
4. What is the difference between single and multilevel inheritances?
5. Explain the concept of defining a derived class in C++ programming language.

Page 139 of 223


Lesson- 11 Implementing Inheritance
Structure
11.0 Objective
11.1 Introduction
11.2 Making a private member Inheritable
11.3 Inheritance Modes
11.4 Single Inheritance
11.5 Multilevel inheritance
11.6 Nesting of classes
11.7Summary
11.8 Glossary
11.9 Answers to check your progress/self assessment questions
11.10 References/ Suggested Readings
11.11 Model questions

11.0 Objective
After studying this lesson, students will be able to:

1. Explain how a private member can be inherited.


2. Describe various modes of inheritance.
3. Implement single level inheritance.
4. Implement multilevel inheritance.
5. Discuss the concept of nested classes.

11.1 Introduction
In the last lesson you learned the fundamentals of inheritance. In this lesson you will learn to
implement inheritance. Two types of inheritances are discussed in lesson namely single inheritance
and multilevel inheritance. As you know that private members cannot be accessed outside the class, in
this lesson you will learn a new access specifier used to access private members of the base class in
the derived class. In the end you will learn the concept of using nesting class. It is quite similar to the
concept of inheritance, but fundamentally is altogether different.

11.2 Making a private member Inheritable


As you already know that a private member cannot be accessed outside the class. Only way to access
a private member outside the class is by using the friend function. Friend function is not a member
function of the class, but C++ programming language provides a provision that you can make a
function friend of a class that is then allowed to access the private members of the class.

Page 140 of 223


Inheritance on the other hand lets the derived class to inherit the features of the base class. You can
access the data members and member functions of the base class directly in derived class. Still there is
restriction that private members of the base class cannot be inherited by the derived class. Only the
member functions and data members declared using public access specifier in the base class can be
accessed directly by the derived class.
Don't worry, there is an option provided by C++ that lets you access the private members of the base
class in the derived class. The option is to use an access specifier in addition to private and public
access specifiers specially meant for inheritance. That additional access specifier is called
protected access specifier.
Protected data members and member functions of the base class can be inherited by the derived class
and can be access directly by it. The private members of the base class that you want to allow the
derived class to inherit can be declared using the protected access specifier. Protected access specifier
is only useful in case of inheritance. Protected members are not accessible outside the class except the
derived class. Hence the protected access specifier should only be used with inheritance. Only those
private members should be declared as protected members that you wish to allow the derived class to
inherit.

11.3 Inheritance Modes


Now that you know three types of access specifiers, the same three also acts as inheritance modes.
Inheritance mode means the access specifier that will be used to inherit the base class. Two things to
consider are
1. The access specifiers used to declare data members and member functions of the base class.
2. Mode used to inherit the members of the base class.
Following is the table that shows the effect of various inheritance modes.

Access Specifiers for the members of Base Class


Inheritance modes
Private Protected Public
Private - Private Private
Protected - Protected Protected
Public - Protected Public
Table 11.1 Inheritance modes
As shown in table 11.1, private members cannot be inherited. Other members can be inherited and
mode in which they are inherited is shown in the table. If you use private mode of inheritance,
members declared using protected and public access specifier of base class convert into the private
members of class deriving it. In case of protected mode of inheritance, both types of members become
the protected members of the derived class. In case of public mode of inheritance, there is no change

Page 141 of 223


in the access specifier of both the protected and public members of the base class. Protected members
of the base class stay the protected members of the derived class and public members of the base class
stay the public members of the derived class.
Check your progress/ Self assessment questions- 1

Q1. How can you inherit the members declared using private access specifier in the base class by the
derived class?

Q2. You can access protected data members of class anywhere outside the class. (TRUE/ FALSE)

Q3. You cannot use private as mode of inheritance. (TRUE/ FALSE)

Q4. What is the use of public mode of inheritance?

11.4 Single Inheritance


Single inheritance is the most basic type of inheritance available that you will learn in this section. In
case of single inheritance, there is only one base class and one derived class. Also there is only single
level of inheritance.

Figure 11.1 Single inheritance.

Page 142 of 223


It is easy to understand the relation as there is only one base and one derived class. There is minimal
complexity and no possibility of ambiguity.

Figure 11.2 Example of single inheritance

Following is the program to implement single inheritance


Program 1
To implement single inheritance

// header files
# include< conio.h >
#include< iostream.h >

// definition of base class student


class student
{
private:
int roll_no, class_no;
char name[20];

public:

void input_details ( )
{

Page 143 of 223


cout<<"Enter the students name :- ";
cin>>name;

cout<<"Enter the students class :- ";


cin>>class_no;

cout<<"Enter the students roll number:- ";


cin>>roll_no;
}

void display_details ( )
{
cout<<"\nStudents name :- "<<name;
cout<<"\nStudents class:- "<<class_no;
cout<<"\nStudents Roll number:- "<<roll_no;
}
};

// definition of derived class marks using public inheritance mode


class marks: public student
{
private:
int math, science, english;

public:
void input_marks ( )
{
cout<<"Enter marks for math :- ";
cin>>math;
cout<<"Enter marks for science :- ";
cin>>science;
cout<<"Enter marks for english :- ";
cin>>english;
}

int compute_avg()
{

Page 144 of 223


int temp;
temp = (math + science + english)/3;
return temp;
}
};

void main ()
{
// object of derived class marks
marks obj1;
int avg;

// call to member functions


obj1.input_details( );
obj1.input_marks();
avg = obj1.compute_avg();
obj1.display_details();
cout<<"\nAverage marks are :- "<<avg;
getch();
}
Base class student is publicly inherited by the derived class marks. The private data members of the
base class are not inherited by the derived class, but the public member functions of the base class are
inherited by the derived class. Object of the derived class has been declared. The same object has then
been used to access the member functions of both base and derived class.

Output:
Enter the students name :- raman
Enter the students class :- 11
Enter the students roll number:- 23
Enter marks for math :- 45
Enter marks for science :- 50
Enter marks for english :- 58

Students name :- raman


Students class:- 11
Students Roll number:- 23

Page 145 of 223


Average marks are :- 51

What if both the base and derived class consists of member functions with same function header
or prototype?
The last example was easy. But what happens if you have member functions with same prototype for
instance in base as well as the derived class. Which member function will be executed in respect to
the function call statement using the object of derived class?

The answer to the above question is; member function of derived class. When object of derived class
is declared, it is automatically bounded to the member function of derived class.

It is ok! But how do you execute member function of base class then? To access the member function
of base class that is same as member function of derived class, you need to take the help of the scope
resolution operator. It explicitly specify the class to which member function belongs to. Consider the
following program for instance:
Program 2
To access base class member using scope resolution operator in single inheritance

// header files
#include<conio.h>
#include<iostream.h>

// definition of base class student


class student
{
private:
int roll_no, class_no;
char name[20];

public:

void input ( )
{
cout<<"Enter the students name :- ";
cin>>name;

cout<<"Enter the students class :- ";

Page 146 of 223


cin>>class_no;

cout<<"Enter the students roll number:- ";


cin>>roll_no;
}

void display ( )
{
cout<<"\nStudents name :- "<<name;
cout<<"\nStudents class:- "<<class_no;
cout<<"\nStudents Roll number:- "<<roll_no;
}
};

// definition of derived class marks using public inheritance mode


class marks: public student
{
private:
int math, science, english;

public:
void input ( )
{
cout<<"Enter marks for math :- ";
cin>>math;
cout<<"Enter marks for science :- ";
cin>>science;
cout<<"Enter marks for english :- ";
cin>>english;
}

int compute_avg()
{
int temp;
temp = (math + science + english)/3;
return temp;
}

Page 147 of 223


};

void main ()
{
// object of derived class marks
marks obj1;
int avg;
// call to member functions
//accessing member function of base class
obj1.student::input( );
// accessing the same member function of derived class
obj1.input();
avg = obj1.compute_avg();
obj1.display();
cout<<"\nAverage marks are :- "<<avg;
getch();
}

In the last program, both base and derived class consists of the member function with same function
header:
void input ()

Following statement is used to call member function of base class:


obj1.student::input( );
Scope resolution operator "student::input( )" specifies that member function input() belongs to the
base class.

Check your progress/ Self assessment questions- 2

Q5. Define Single inheritance.

Q6. If base and derived class have member functions with the same prototype, member function of
which class is executed when called using object of derived class?

Page 148 of 223


Q7. If base and derived class have member functions with the same prototype, how can you access the
member function of the base class using the object of derived class?

11.5 Multilevel inheritance


Multilevel inheritance is an extension of single level inheritance. The structure is same as that of
single inheritance only adding to the number of levels. It means that there still is one base and one
derived class only, but the derived class at level 1 acts as base class for derived class at level 2 and so
on.

Figure 11.3 Multilevel inheritance

Program 3
To implement multilevel inheritance
// header files
#include<iostream.h>
#include<conio.h>

//base class level 0


class student

Page 149 of 223


{
protected:
int roll_no;
public:
void get_roll_no(int no)
{
roll_no=no;
}
void display()
{
cout<<"\nRoll number of the student is :- "<<roll_no;
}
};

//derived class at level 1 which is base class of derived class at level 2


class test: public student
{
protected:
int math, science;
public:
void get_marks (int no1,int no2)
{
math = no1;
science = no2;
}
void display()
{
cout<<"\nMarks in math :- "<<math;
cout<<"\nMarks in science :- "<<science<<"\n";
}
};

//derived class at level 2


class result: public test
{
int average;
public:

Page 150 of 223


void display()
{
average = (math + science)/2;
//class to display member function of base class at level 0
student::display();
//class to display member function of intermediate base class at level 1
test::display();
cout<<"\nAverage marks = "<<average;
}
};

void main()
{
// object of derived class at level 2
result obj1;
//call to member functions
obj1.get_roll_no(12);
obj1.get_marks(75, 85);
obj1.display();
getch();
}

Interesting concept in this program is nesting of member functions. Look at the following definition
of member function display() of the result derived class:

void display()
{
average = (math + science)/2;
//class to display member function of base class at level 0
student::display();
//class to display member function of intermediate base class at level 1
test::display();
cout<<"\nAverage marks = "<<average;
}

The definition of the member function also includes the function call statements to the member
functions of base classes student and test. When you call the member function display of derived class

Page 151 of 223


from the main ( ), indirect call is made to the display ( ) of both the student and test classes which are
nested into the display ( ) of the derived class result.

Output:
Roll number of the student is :- 12
Marks in math :- 75
Marks in science :- 85
Average marks = 80

How do constructors get called in case of multilevel inheritance


You can create a class using inheritance by inheriting the features of already defined base class. You
can then access the features of the base class using the object of the derived class and there is no need
to create the object of the base class.
If an object of base class is not created, what happens to constructor of base class. Does it get called?
The answer is, yes. When object belonging to derived class is created, an automatic call is send to
constructors of the base classes along with the constructor function of derived class. Also the order of
calling is of your interest. In case of multilevel inheritance, the constructor of base class at level 0 is
initially called and then constructor of intermediate base class and finally the constructor from derived
class at level 2 and so on.

Program 4
To demonstrate the calling of constructor's in case of multilevel inheritance

// header files
#include<conio.h>
#include<iostream.h>

// definition of base class at level 0


class base0
{ public:
base0 ( )
{
cout<<"\nConstructor function of base class at level 0";
}
};

Page 152 of 223


// definition of intermediate base class at level 1
class base1
{
private:
public:
base1 ( )
{
cout<<"\nConstructor function of base class at level 1";
}
};

// definition of derived class at level 2


class derived2
{ private:
public:
derived2 ( )
{
cout<<"\nConstructor function of derived class at level 2";
}
};

void main ()
{
// object of derived class at level 2
derived2 obj1;
getch();
}

Output:
Constructor function of base class at level 0
Constructor function of base class at level 1
Constructor function of derived class at level 2

11.6 Nesting of classes

Page 153 of 223


Nesting of classes is an interesting concept. Sometimes it is taken as an alternative to inheritance, but
in actual it is not an alternative to inheritance. You cannot get the benefits of the protected access
specifier in case of nested classes.

What is a nested class? When you declare an object of 1 class as data member of other class, first
class becomes nested class of second class. You can then use the object of nested class to access
public members of nested class. Second class is neither friend class of the first class nor it inherits the
features of the first class. It is a simple concept where in you create the object of 1 class as member of
other class.

Program 5
To implement nesting of class

// header files
#include<conio.h>
#include<iostream.h>

// definition of class to be nested


class student
{
private:
int roll_no, class_no;
char name[20];
public:
void input ( )
{
cout<<"Enter the students name :- ";
cin>>name;
cout<<"Enter the students class :- ";
cin>>class_no;
cout<<"Enter the students roll number:- ";
cin>>roll_no;
}
void display ( )
{
cout<<"\nStudents name :- "<<name;
cout<<"\nStudents class:- "<<class_no;

Page 154 of 223


cout<<"\nStudents Roll number:- "<<roll_no;
}
};

// definition of class that will implement nesting of class


class marks
{
private:
int math, science, english, avg;
//object of class student
student s1;
public:
void input ( )
{
//call to member function of class student
s1.input();
cout<<"Enter marks for math :- ";
cin>>math;
cout<<"Enter marks for science :- ";
cin>>science;
cout<<"Enter marks for english :- ";
cin>>english;
}
void compute_avg()
{
avg = (math + science + english)/3;
}
void display ( )
{
//call to member function of class student
s1.display();
cout<<"\nAverage marks are :- "<<avg;
}
};

void main ()

Page 155 of 223


{
// object of class marks
marks obj1;
// call to member functions
obj1.input( );
obj1.compute_avg();
obj1.display();
getch();
}

Data members of class marks includes object of class student which makes the class student a nested
class of class marks. What is the difference between inheritance and nested class?

Look at the following statement used to access the member function of nested class:
//call to member function of class student
s1.input();
Rather than using the scope resolution operator, the member function is accessed using the dot
operator with object name of the nested class.

Check your progress/ Self assessment questions- 3

Q8. Define multilevel inheritance.

Q9. In case of multilevel inheritance, derived class can be used as base to class to derive another class
(TRUE/ FALSE).

Q10. When you create the object of the derived class, an automatic call is send to the constructors of
the base classes along with the constructor of derived class. (TRUE/FALSE)

11.7 Summary

Page 156 of 223


Private member cannot be accessed outside the class. Only way to access a private member outside
the class is by using the friend function. Inheritance lets derived class to inherit features of base class.
Protected data members and member functions of base class are inherited by derived class and can be
access directly by it. Protected access specifier is only useful in case of inheritance. Protected
members are not accessible outside the class except the derived class.

If you use private mode of inheritance, members declared using protected and public access specifier
of base class convert into the private members of class deriving it. In case of protected mode of
inheritance, both types of members become the protected members of the derived class. In case of
public mode of inheritance, there is no change in the access specifier of both the protected and public
members of the base class. Protected members of the base class stay the protected members of the
derived class and public members of the base class stay the public members of the derived class.

In case of single inheritance, there is only one base class and one derived class. Also there is only
single level of inheritance. If you have member functions with same prototype for instance in both the
base and derived class, member function of the derived class is executed when the member function is
called using the object of derived class. To access member function of base class that is same as
member function of derived class, take the help of scope resolution operator.

When object belonging to derived class is created, an automatic call is send to constructors of the base
classes along with the constructor function of derived class. Also the order of calling is of your
interest. In case of multilevel inheritance, the constructor of base class at level 0 is initially called and
then constructor of intermediate base class and finally the constructor from derived class at level 2
and so on. When you declare an object of 1 class as data member of other class, first class becomes
nested class of second class.

11.8 Glossary
Inheritance- OOP concept used to create a new class by inheriting the features of an old class.
Single inheritance- It comprises of only one base class and one derived class. Also there is only single
level of inheritance.
Multilevel inheritance- It is an extension of single level inheritance only adding to the number of
levels.
Base class- Class whose features are used to create a derived class with the help of inheritance.
Derived class- Newly created class by inheriting the features of base class using the concept of
inheritance .

Page 157 of 223


Nested class- When you declare an object of one class as data member of another class, first class
becomes the nested class of the second class.

11.9 Answers to check your progress/self assessment questions


1. Declare the private members of the base class using protected access specifier that can be inherited
by the derived class and can be accessed directly by it. Protected access specifier is only useful in case
of inheritance. Protected members are still not accessible outside the class except the derived class.

2. FALSE.
3. FALSE.
4. In case of public mode of inheritance, there is no change in the access specifier of both the
protected and public members of the base class. Protected members of the base class stay the
protected members of the derived class and public members of the base class stay the public members
of the derived class.
5. Single inheritance consists of only one base class and one derived class. Also there is only single
level of inheritance. It means the derived class is not used as intermediate base class to derive another
class.
6. Derived class.
7. If base and derived class have member functions with the same prototype, to access the member
function of the base class you need to take the help of the scope resolution operator. Scope resolution
operator is used to explicitly specify the class to which the member function belongs to.
8. Multilevel inheritance is an extension of single level inheritance only adding to the number of
levels. It means that there still is one base and one derived class only, but the derived class at level 1
acts as base class for derived class at level 2 and so on.
9. TRUE.
10. TRUE.

11.10 References/ Suggested Readings

1. Balagurusamy, Object Oriented Programming with C++, 3rd Edition, Tata McGraw-Hill
Education, 2006.
2. Lafore R, Object Oriented Programming in C++, 4th Edition Waite Group, 2002.
3. R. S. Salaria, Mastering Object-Oriented Programming with C++, Salaria Publishing House.

11.11 Model questions


1. Explain the concept of nested class with the help of a program.

Page 158 of 223


2. Explain the calling mechanism of constructors using inheritance with the help of a program.
3. Write a program to access member function of both base and derived class having same prototype.
4. How can you inherit the private members of the base class?
5. Explain the three modes of inheritance.

Page 159 of 223


Lesson- 12 Polymorphism and function overloading
Structure
12.0 Objective
12.1 Introduction
12.2 Polymorphism
12.3 Types of polymorphism
12.4 Function Overloading
12.5 Constructor overloading
12.6 Summary
12.7 Glossary
12.8 Answers to check your progress/self assessment questions
12.9 References/ Suggested Readings
12.10 Model questions

12.0 Objective
After studying this lesson, students will be able to:
1. Define polymorphism.
2. Discuss types of polymorphism.
3. Explain the concept of function overloading.
4. Implement function overloading.
5.Implement constructor overloading.

12.1 Introduction
Polymorphism is a key feature of Object Oriented Programming. In this lesson you will come across
different types of polymorphism that can be achieved using C++ programming language. Only the
function overloading is discussed in this lesson and other types of polymorphism are discussed in the
next two lessons of this SLM. The lesson also includes the implementation of function overloading.
You are already familiar of a special member function called constructor function. This lesson also
discusses the overloading of constructor function of class.

12.2 Polymorphism
Polymorphism means something having multiple or many forms. In C++ programming language,
polymorphism is also known as overloading. C++ allows to create multiple functions of the same
name and also give new meaning to already defined operators.

12.3 Types of polymorphism


C++ broadly provides following types of polymorphism:

Page 160 of 223


Figure 12.1 Polymorphism types
Compile Time Polymorphism:
In case of compile time polymorphism, C++ compiler is provided enough information about the
entities that helps the compiler bind these entities to the respective statements used to call these
executions. Once the binding is done during compile time, the same cannot be changed later on. Two
entities for which the compile time binding can be achieved in C++ programming language are as
follows:
Function Overloading- C++ programmers can create multiple function definitions with the same
function name and the compiler is able to bind these definitions with respective function call
statements based on number of arguments or type of function arguments.
Operator Overloading: It is a very powerful feature of C++. You can overload the valid operators used
in C++ programming language. In addition to their predefined meaning, programmers can overload
these operators and re-define them for class objects.

Run time Polymorphism:


Run time polymorphism is also known as late binding. Run time polymorphism is implemented with
the help of pointers. Binding of the entities is postponed during compile phase and binding is done at
run time. Virtual function is an example of run time binding.
Check your progress/ Self assessment questions- 1

Q1. Define polymorphism.

Q2. Once the binding is done during compile time, the same cannot be later on.
Q3. Run time polymorphism is implemented with the help of .

Q4. is an example or run time binding.

12.4 Function Overloading

Page 161 of 223


Function overloading is compile time polymorphism or overloading. It is also called function
polymorphism. Function overloading is used to create multiple functions of the same name. Seems
impossible but it is possible. The compiler is able to differentiate between the multiple functions of
the same name and bind them to appropriate function call statements. In this section, you will learn
the methods using which the function overloading can be achieved and how the additional
information is used by the compiler to differentiate between the functions during compile time.

You can create one complete set of functions with the same name that are capable of performing
different operations. These functions consists of different set of argument lists that is used to
differentiate between them and the kind of operations they can perform also depends on the argument
list of each function.

Compiler is able to bind the function with appropriate function call statement at the compile time
using the number of arguments in the argument list and the type of arguments. Compiler in C++
programming language cannot differentiate between the two functions with same name on the basis of
their return type.

Wherever a function call statement to an overloaded function is encountered, the compiler first checks
for the prototype of function with the same number of arguments and same type. If the compiler does
not find any function prototype or more than one function prototype that matches the function call
statement, it raises an error. For the first case, the error raised is prototype for the function not found
and for the second case, the error raised is for ambiguity. It means that for every function call
statement, the compiler should be able to match it with a unique prototype.

Once the compiler is able to find a unique match for the function call statement in form of function
prototype, the appropriate function is called for execution. In case the compiler is able to find a
function prototype that matches in respect of number of arguments, but not in respect of argument
types, the compiler uses the concept of integral promotion of the actual arguments. For example, char
to int or float to double.

If the integral promotion also does not work, then the compiler tries the implicit conversions to the
actual arguments. It is also called the implicit type casting. But using the implicit type casting can also
result in eventually the function call statement matching with two function prototypes. For example,
you call add ( int ) function and pass integer argument to it. The program consists of two add ( )
functions, one with formal argument of long type and one with formal argument of double type. First
of all the compiler fails to find the exact match and then it tries the integral promotion of actual
arguments which also fails. Then it tries the implicit type conversion of actual argument. Implicit type

Page 162 of 223


conversion of actual argument will lead to ambiguity error as the integer type can be implicitly
converted to both the long and double type.
Now you will see programs that will help you better understand the concept of function overloading.

Check your progress/ Self assessment questions- 2

Q5. How can you achieve function overloading?

Q6. If the integral promotion also does not work, then the compiler tries the
to the actual arguments.

Q7. Function overloading is polymorphism or overloading.

Program 1
To find the sum of two numbers
//header files
# include < iostream.h >
# include < conio.h >
//definition of class
class add

{
private:
int var1 ;
int var2 ;
public:
// default constructor function
add ( )

{
var1 = 0 ;
var2 = 0 ;

}
void set ( int a, int b )
{

Page 163 of 223


var1 = a ;
var2 = b ;
}
void display ( )

{
cout<<" \n Value of data member var1 :- " << var1 ;
cout<<" \n Value of data member var2 :- " << var2 ;
cout<<" \n Sum of two data members is :- " << var1 + var2 ;
}

};
void main( )
{
// object of class add
add obj1;

float a = 12.5 , b = 13.3 ;


//call to member function of obj1
obj1.set ( a , b );
// call to member function of obj1
obj1.display( ) ;
getch();
}

Will this program execute successfully? Must be wondering! what's wrong with this program.
Inside the main ( ), one object of class add is declared using the following statement:
// object of class add
add obj1;

It is followed by a statement used to call the member function of class add:


//call to member function of obj1
obj1.set ( a , b );

Which member function will be called? Must be wondering again! What's so difficult in the question.
Obviously the following member function of class add will be called:
void set ( int a , int b )
{

Page 164 of 223


var1 = a ;
var2 = b ;
}
Wait! The formal arguments used in the member function are of integer data type and actual
arguments passed in the function call statement are of float type. The answer to the question whether
the program will execute successfully or not is, yes.

Once the compiler fails to find a member function that exactly matches the function call statement,
compiler tries the implicit conversions to the actual arguments. The actual arguments of float type are
implicitly type casted to integer type and member function set ( ) is called for execution.

Output:
Value of data member var1 :- 12
Value of data member var2 :- 13
Sum of two data members is :- 25
Because the actual arguments are type casted to integer type, the actual values passed to the formal
arguments are 12 and 13 respectively.

Program 2
To implement overloading of sum function (keeping type of arguments different)
//header files
# include < iostream.h >
# include < conio.h >
//definition of class
class add
{
private: int
var1 ; int
var2 ; float
var3 ; float
var4 ;
public:
// default constructor function
add ( )
{
var1 = 0 ;

Page 165 of 223


var2 = 0 ;
}
//overloaded function with integer arguments
int sum ( int a, int b )
{
cout<< " \n Function to add two integer numbers " ;
var1 = a ;
var2 = b ;
return ( var1 + var2 ) ;
}
//overloaded function with float arguments
float sum ( float a, float b )
{
cout<< \n Function to add two float numbers " ;
var3 = a ;
var4 = b ;
return ( var3 + var4 ) ;
}
};
void main( )
{
// object of class add
add obj1;
float fa = 12.5 , fb = 13.3 , ftotal ;
int ia = 18 , ib = 20 , itotal ;
//call to overloaded member function using float arguments
ftotal = obj1.sum( fa , fb );
cout<< " \n Sum of " << fa << " and " << fb << " is " << ftotal ;
//call to overloaded member function using integer arguments
itotal = obj1.sum( ia , ib );
cout<< " \n Sum of " << ia << " and " << ib << " is " << itotal ;
getch();
}

In the last program function sum ( ) is overloaded.


int sum ( int a, int b )
float sum ( float a, float b )

Page 166 of 223


Both the functions share the same name. The first instance accepts two integer arguments and the
second instance accepts two float arguments. Following function call statement will result in the
execution of member function with formal arguments of integer type:
itotal = obj1.sum( ia , ib );
Because the actual arguments are also of the integer type. Similarly, the following function call
statement will result in the execution of member function with formal arguments of float type:
ftotal = obj1.sum( fa , fb );
Because the actual arguments are also of float type.

Output:
Function to add two float numbers
Sum of 12.5 and 13.3 is 25.8
Function to add two integer numbers
Sum of 18 and 20 is 38

Program 3
To implement overloading of average function (keeping number of arguments different)
//header files
# include < iostream.h >
# include < conio.h >
//definition of class
class average
{
private:
int var1 ;
int var2 ;
int var3 ;
public:
// default constructor function
average ( )
{
var1 = 0 ;
var2 = 0 ;
var3 = 0 ;
}
//overloaded function with 2 integer arguments

Page 167 of 223


int compute ( int a, int b )
{
cout<< " \n Function to find average of two integer numbers " ;
var1 = a ;
var2 = b ;
return ( ( var1 + var2 ) / 2 ) ;
}
//overloaded function with 3 integer arguments
int compute ( int a, int b , int c )
{
cout<< " \n Function to find average of three integer numbers " ;
var1 = a ;
var2 = b ;
var3 = c ;
return ( ( var1 + var2 + var3 ) / 3 ) ;
}
};
void main( )
{
// object of class average
average obj1;
int a = 10 , b = 20 , c = 30 , avg ;
//call to overloaded member function using 2 arguments
avg = obj1.compute ( a , b );
cout<< " \n Average of " <<a << " and " << b << " is " <<avg ;
//call to overloaded member function using 3 arguments
avg = obj1.compute ( a , b , c );
cout<< " \n Average of " <<a << " , " << b <<" and " << c <<" is " <<avg ;
getch();
}

In the last program function compute ( ) is overloaded.


int compute ( int a, int b )
int compute ( int a, int b , int c )

Page 168 of 223


Both the functions share the same name. The first definition accepts two integer arguments and the
second instance accepts three integer arguments. Following function call statement will result in the
execution of member function with formal arguments of 2 integers:
avg = obj1.compute ( a , b );
and the following function call statement will result in the execution of member function with formal
arguments of 3 integers:
avg = obj1.compute ( a , b , c );

Output:
Function to find average of two integer numbers
Average of 10 and 20 is 15
Function to find average of three integer numbers
Average of 10, 20 and 30 is 20

12.5 Constructor overloading


Constructor is a special member function that is automatically called when the object of the same
class is created. You can also overload the constructor function, i.e. have multiple constructor
functions in the member list of the same class.

Program 4
To implement constructor overloading
//header files
# include < iostream.h >
# include < conio.h >
//definition of class
class add
{
private:
int var1 ;
int var2 ;
public:
// default constructor function
add ( )
{
cout<<" \n Default constructor called " ;
var1 = 0 ;
var2 = 0 ;
}

Page 169 of 223


// parameterized constructor function
add ( int a , int b )
{
cout<<" \n Parameterized constructor called " ;
var1 = a ;
var2 = b ;
}
// copy constructor function
add ( add & obj )
{
cout<<" \n Copy constructor called " ;
var1 = obj.var1 ;
var2 = obj.var2 ;
}
void display ( )
{
cout<< " \n Value of var1 = " << var1 << " and var2 = " << var2 ;
}
};
void main( )
{
// objects of class add
add obj1;
add obj2 ( 10 , 20 ) ;
add obj3 ( obj2 ) ;
cout<< " \n Value of data members with default constructor " ;
obj1.display ( ) ;
cout<< " \n Value of data members with parameterized constructor " ;
obj2.display ( ) ;
cout<< " \n Value of data members with copy constructor " ;
obj3.display ( ) ;
getch();
}
Output:
Default constructor called
Parameterized constructor called

Page 170 of 223


Copy constructor called
Value of data members with default constructor
Value of var1 = 0 and var2 = 0
Value of data members with parameterized constructor
Value of var1 = 10 and var2 = 20
Value of data members with copy constructor
Value of var1 = 10 and var2 = 20

12.6 Summary
Polymorphism means something having multiple or many forms. In C++ programming language,
polymorphism is also known as overloading. In case of compile time polymorphism, C++ compiler is
provided enough information about the entities that helps the compiler bind these entities to the
respective statements used to call these executions. Once the binding is done during compile time, the
same cannot be changed later on. C++ programmers can create multiple function definitions with the
same function name and the compiler is able to bind these definitions with respective function call
statements based on number of arguments or type of function arguments. You can also overload the
valid operators used in C++ programming language. In addition to their predefined meaning,
programmers can overload these operators and re-define them for class objects. Run time
polymorphism is also known as late binding. Run time polymorphism is implemented with the help of
pointers. Binding of the entities is postponed during compile phase and binding is done at run time.
Virtual function is an example of run time binding.
Function overloading is compile time polymorphism or overloading. It is also called function
polymorphism. Function overloading is used to create multiple functions of the same name. These
functions consists of different set of argument lists that is used to differentiate between them and the
kind of operations they can perform also depends on the argument list of each function.
In case the compiler is able to find a function prototype that matches in respect of number of
arguments, but not in respect of argument types, the compiler uses the concept of integral promotion
of the actual arguments. If the integral promotion also does not work, then the compiler tries the
implicit conversions to the actual arguments.
Constructor is a special member function that is automatically called when the object of the same
class is created. You can also overload the constructor function, i.e. have multiple constructor
functions in the member list of the same class.

12.7 Glossary
Polymorphism- Polymorphism means something having multiple or many forms.C++ allows to create
multiple functions of the same name and also give new meaning to already defined operators.

Page 171 of 223


Function overloading- Creating multiple functions with the same name.
Operator overloading- Overloading or re-defining already defined operators.
Virtual function- Member function of the base class defined using virtual keyword. It is an example of
run time polymorphism.
Pointer- Variable used to store the address of another variable or reference.
Constructor- Member function of a class called automatically when the object of the same class is
created.

12.8 Answers to check your progress/self assessment questions


1. Polymorphism means something having multiple or many forms. In C++, polymorphism is also
known as overloading. C++ allows to create multiple functions of the same name (called function
overloading) and also give new meaning to already defined operators (called operator overloading).
2. changed.
3. pointers.
4. Virtual function.
5. Function overloading can be achieved by using different number of arguments in the argument list
or by having different types of arguments in the argument list. You cannot achieve function
overloading by having different return types.
6. implicit conversions.
7. compile time.
12.9 References/ Suggested Readings
1. Balagurusamy, Object Oriented Programming with C++, 3rd Edition, Tata McGraw-Hill
Education, 2006.
2. Lafore R, Object Oriented Programming in C++, 4th Edition Waite Group, 2002.
3. R. S. Salaria, Mastering Object-Oriented Programming with C++, Salaria Publishing House.

12.10 Model questions


1. Write a program to overload constructor function.
2. What is compile time polymorphism.
3. What additional steps are taken by compiler if it fails to find a function prototype that exactly
matches with the function call statement?
4. What is polymorphism and list various types of polymorphisms in C++?
5. What is function overloading? Write a program to implement function overloading.

Page 172 of 223


Lesson- 13 Operator Overloading
Structure
13.0 Objective
13.1 Introduction
13.2 Operator overloading
13.2.1 Operator Function
13.3Overloading Unary operator
13.4 Overloading Binary operator
13.5Summary
13.6 Glossary
13.7 Answers to check your progress/self assessment questions
13.8 References/ Suggested Readings
13.9 Model questions

13.0 Objective
After studying this lesson, students will be able to:
1. Explain the need of operator overloading.
2. Implement unary operator overloading.
3. Differentiate between overloading pre-increment and post-increment operator.
4. Implement binary operator overloading.

13.1 Introduction
You must have heard of the term operator a number of times already in this SLM and in the first
semester too. In this lesson you will come to face with another dimension of operator. Just like a
function, you can also create many forms of operators, i.e. you can also overload the operators. Only
difference between function and operator overloading is that in case of operator overloading, its
original meaning cannot be changed and is already defined by the compiler, you are simply adding
more forms to it. In this lesson you will learn each and every concept of operator overloading and also
learn to implement both the unary and binary operators.

13.2 Operator overloading


Operator overloading is a key concept of C++ programming. Operator overloading is a type of
polymorphism and is used to give new meaning or create multiple forms of operators already
available in programming language. A number of operators are available in C++ programming
language. Each operator in C++ has a pre-defined meaning. The output for the same is also according
to its pre-defined meaning.
For example,
Plus operator '+' is used to find the sum of two numbers.
For instance,
Page 173 of 223
a = 12 + 13
here the '+' operator will add '12' and '13' and the output is '25' which will be assigned to 'a'. In the last
statement assignment operator '=' is also used with '+' operator. Assignment operator is used to assign
the outcome of expression on right side of assignment operator to the variable on left side of
assignment operator.

Now, you are clear with the concept of operator and its operating rules and regulations. Operator
overloading is the concept of giving new meanings to already available operators in C++.
Overloading an operator does not change the basic meaning of the operator. The overloaded operator
still behaves the same when it is applied to non class objects or types like integer, float or char.
Only the operators that are pre-defined by C++ compiler can be overloaded. Overloading is done to
give new meaning to these operators and operator overloading cannot be used to create or define new
operators. Overloading an operator is restricted to giving additional meaning to the operator and you
cannot change the behavioral attributes of the operator. By behavioral attributes, we mean the
precedence, associativity and syntax for the operator.

Once an operator is overloaded, it can be applied on class objects just as you apply the operators on
built-in data types.

Consider the following statement for example,


Class_Object1 = Class_Object2 + Class_Object3

Let us consider that plus '+' operator has been overloaded for some class and Class_Object1,
Class_Object2, and Class_Object3 are 3 objects of the same class. '+' in the last statement is treated as
function called operator function. Operator function is discussed in the next section. Interestingly not
all operators available in C++ can be overloaded.

Following is the list of some of the operators that cannot be overloaded in C++ programming
language:

Scope resolution operator ::


Dot operator .
Conditional operator ?:
Pointer-to-member operator .*
Preprocessor #
sizeof()

Page 174 of 223


1. Conditional operator cannot be overloaded because it is applied on 3 operands and C++ does not
provide mechanism to overload the same.

2. sizeof() operator is used for certain built-in operations. Like incrementing a pointer variable to
access each element of an array implicitly. Hence it is not overloaded as it can lead to confusion. For
similar reasons the overloading of # operator is also avoided in C++.

3. It is also not feasible to overload the scope resolution operator (::). Consider for example,
student::input, both the student and input are identifiers known to compiler and are not any
expressions or variables that represent some value. Also the :: operator is used to perform scope
resolution at compile time rather than evaluate the expression.

4. It may be possible to overload the dot (.) operator. But it may lead to some confusion. If the dot (.)
is eventually overloaded, the question may arise if the dot is used for object overloading or to access
an object referred to by dot (.) operator. For same reasons overloading of the Pointer-to-member
operator .* is also avoided in C++.

Check your progress/ Self assessment questions- 1

Q1. List various operators that cannot be overloaded in C++?

Q2. Which operators can be overloaded and what is the objective of overloading operators in C++?

Q3. Why the :: operator cannot be overloaded in C++?

Page 175 of 223


13.2.1 Operator Function

Operator overloading can be achieved with the help of a special function called the operator function.
It means you have to write a function in order to overload an operator and it shares all the features of a
normal function in C++. The operator function will also have a function header, function body that
can contain a return statement just like any function in C++. The body of the operator function
determines the operation to be performed by it and it can be different from the normal behavior of that
operator. Hence it is the body of the operator function that determines the new meaning of the
operator.
Beside all the similarities, there are a few differences between the function header of normal function
and the operator function.
Following is the syntax for function header of a normal function

Return_Type Function_name (Argument_List)


Whereas following is the function header of an operator function.
Return_Type operator Operator_Symbol ( Argument list )

The difference between the two is in the function identifier or function name. You are free to choose
any valid identifier for the normal function. But the identifier for the operator function is the operator
symbol pre-defined by the C++ compiler and is followed by the keyword operator to tell the compiler
that it is an operator function.

Consider the following function header for the operator function to overload the binary plus '+'
operator:
Class_Name operator + (Class_name Object_name)

Also the function call statement for the operator function is different from the function call statement
of the normal member function. You place call to the member function using the dot (.) operator and
call to the operator function is placed using the operator symbol pre-defined by the compiler. For
example, you want to find the sum of two objects and assign it to the third object, the same can be
achieved using a call to the member function as follows:
Object_Name1 = Object_Name2.Function_Name(Object_Name3);

And the same can be achieved using a call to operator function as follows:
Object_Name1 = Object_Name2 + Object_Name3;

Page 176 of 223


13.3Overloading Unary operator
Unary operators are used to apply operator on single operand. Some of the examples of unary
operators in C++ programming are ++, --, +, -, !, ~. Operator function for overloading unary operator
does not have any argument in the argument list. In this section you will learn the implementation of
overloading unary minus '-' operator and also overloading increment operator. Increment operator
comes in two variations known as post increment and pre increment. Treatment of both variations of
increment operator are different in C++ and has also been discussed latter in this lesson. Following is
the program to overload the unary minus operator.

Program 1
To overload the unary minus '-' operator
//header files
#include<iostream.h>
#include<conio.h>
//class definition
class MINUS
{
private:
int var1;
public:
//constructor
MINUS ()
{
var1 =0;
}
void input()
{
cout<<”\nEnter the value of member var1 :- “;
cin>>var1;
}
// definition of operator function for unary '-' operator
MINUS operator - ()
{
MINUS temp;
temp.var1 = -var1;
return temp;

Page 177 of 223


}
void display()
{
cout<<"\nValue of member var1 :- "<<var1;
}
};

void main()
{
//objects of class MINUS
MINUS obj1, obj2;
//call to member function of obj1
obj1.input();
//call to operator function for overloading unary minus '-' operator
obj2 = -obj1;
//call to member function of obj1
obj2.display();
getch();
}

Following is the operator function used in the last program to overload the unary minus '-' operator:
MINUS operator - ()
{
MINUS temp;
temp.var1 = -var1;
return temp;
}
Return type is the class type itself. The statement used to call the operator function:
obj2 = -obj1;
Here the call to the operator function is done for the object obj1 and the temp object returned in the
operator function is assigned to obj2.

Output:

Enter the value of member var1 :- 45


Value of member var1 :- -45

Page 178 of 223


As already stated earlier in this SLM, overloading the increment or decrement operator comes in two
variations. One is overloading the pre increment operator and one is overloading the post increment
operator. C++ provides its users with the mechanism to differentiate between the two. If the
programmer explicitly does not differentiate between the two, then the same operator function is used
for both the pre increment and post increment operators.

Following is the program where only one operator function is used for both types of increments.

Program 2
To implement increment operator '++' using single operator function

//header files
#include <iostream.h>
#include<conio.h>
//definition of class
class INC
{
private:
int var1;
public:
//constructor function
INC( )
{
var1= 0;
}
void input ( )
{
cout<<”\nEnter value for data member var1 :- “;
cin>>var1;
}
// definition of operator function to overload increment operator '++'
void operator ++ ( )
{
var1++;
}
void display( )
{

Page 179 of 223


cout<<”\nValue of data member var1 :- “<<var1;
}
};

void main( )
{
// object of class INC
INC obj1;
//call to member function of obj1
obj1.input( );
// call to operator function '++'
obj1++;
// call to operator function '++'
++obj1;

// call to member function of obj1


obj1.display();
getch();
}

The only operator function used in the last program is:


void operator ++ ( )
{
var1++;
}

And the program consists of two operator function call statements:


// call to operator function '++'
obj1++;
// call to operator function '++'
++obj1;

The first statement uses the post increment scheme and the second statement uses the pre increment
scheme. Because the program is written using a single operator function and the program also does
not explicitly differentiate between pre and post increment, same operator function is executed for
both the operator function call statements.

Page 180 of 223


Output:
Enter value for data member var1 :- 47
Value of data member var1 :- 49

Check your progress/ Self assessment questions- 2

Q4. What is an operator function?

Q5. Can a single operator function work for both post and pre increment function call statements?

It is possible to create two separate operator functions for post increment and pre increment schemes.
The compiler is able to differentiate between the two at compile time and able to bind the function
call statements to their respective operator functions.

Program 3
To overload both the post and pre increment operators

//header files
#include <iostream.h>
#include<conio.h>
//class defintion
class INC
{
private:
int var1;
public:
//constructor function
unaryinc ( )
{

Page 181 of 223


var1 = 0;
}
void input ( )
{
cout<<”\nEnter value of data member var1 :- “;
cin>>var1;
}
// definition of operator function for pre increment scheme
INC operator ++ ( )
{
INC temp;
var1++;
temp.var1 = var1;
return temp;
}
// definition of operator function for post increment scheme
INC operator ++ ( int )
{
INC temp;
temp.var1 = var1;
var1++;
return temp;
}
void display( )
{
cout<<”\nValue of member function var1 :- “<<var1;
}
};

void main( )
{
// objects of class INC
INC obj1, obj2;

cout<<”\nObject 1”;
//call to memebr function of obj1
obj1.input( );

Page 182 of 223


// call to pre increment operator function
obj2 = ++obj1;
cout<<”\nValue of data member var1 of object1 after pre increment”;
obj1.display();
cout<<”\nValue of data member var1 of object2 after pre increment”;
obj2.display();
// call to post increment operator function
obj2 = obj1++;
cout<<”\nValue of data member var1 of object1 after post increment”;
obj1.display();
cout<<”\nValue of data member var1 of object2 after post increment”;
obj2.display();
getch();
}

Two separate operator functions are used in the last program:


FOR OVERLOADING PRE INCREMENT OPERATOR
INC operator ++ ( )
{
INC temp;
var1++;
temp.var1 = var1;
return temp;
}
The function header is same as that of the function header of operator function used in the program
previous to this. The value of data member var1 is incremented first and then assigned to the data
member var1 of temp object before it is returned.

FOR OVERLOADING POST INCREMENT OPERATOR


INC operator ++ (int )
{
INC temp;
temp.var1 = var1;
var1++;
return temp;
}

Page 183 of 223


The function header is slightly different from the function header of operator function used for
overloading pre increment operator. As you can see in the function header of operator function for the
post increment operator, 'int' is passed as argument. The value of data member var1 is assigned to the
data member var1 of temp object and is increment after that. Hence the temp object returns the non-
incremented value.

Output:
Object 1
Enter value of data member var1 :- 10

Value of data member var1 of object1 after pre increment


Value of member function var1 :- 11
Value of data member var1 of object2 after pre increment
Value of member function var1 :- 11

Value of data member var1 of object1 after post increment


Value of member function var1 :- 12
Value of data member var1 of object2 after post increment
Value of member function var1 :- 11

13.4 Overloading binary operator

Overloading binary operator is slightly difficult than overloading a unary operator. Binary operator is
used to perform operation on two operands. All arithmetic operators are examples of binary operators.
In case of overloading unary operator, no arguments were passed to the operator function. But in case
of overloading binary operator, one object is passed as argument to the operator function. Consider
the following statement which is an operator function call statement:
Object_Name1 = Object_Name2 + Object_Name3;
The Object_Name2object places call to its operator function '+' and Object_Name3 is passed as
argument to the function. The addition of two objects is then returned to Object_Name1. Following is
the program to overload the binary plus '+' operator.

Program 4
To overload binary operator plus '+'
//header files
#include <iostream.h>
#include<conio.h>

Page 184 of 223


//class definition
class ADD
{
private:
int var1;
int var2;
public:
//constructor function
ADD( )
{
var1 = 0;
var2 = 0;
}
void input ( )
{
cout<<”\nEnter value of data member var1 :- “;
cin>>var1;

cout<<”\nEnter value of data member var2 :- “;


cin>>var2;
}
//definition of operator function to overload binary plus '+' operator
ADD operator + ( ADD obj3 )
{
ADD temp;
temp.var1 = var1 + obj3.var1;
temp.var2 = var2 + obj2.var2;
return temp;
}
void display( )
{
cout<<”\nValue of data member var1 :- “<<var1;
cout<<”\nValue of data member var2 :- “<<var2;
}
};

void main( )

Page 185 of 223


{
ADD obj1, obj2, obj3;
cout<<”\nObject 2”;
//call to member function of object 2
obj2.input( );
cout<<”\nObject 3”;
//call to member function of object 3
obj3.input( );
// call to the operator function '+'
obj1 = obj2 + obj3;
cout<<”\nObject 1 after addition”;
obj1.display();
getch();
}

Last program is used to overload the binary operator '+' using the following operator function:
ADD operator + ( ADD obj3 )
{
ADD temp;
temp.var1 = var1 + obj3.var1;
temp.var2 = var2 + obj2.var2;
return temp;
}
The function call statement used to call the operator function:
obj1 = obj2 + obj3;

obj3 is passed as actual argument. obj2 is the object that places call to the operator function.
temp.var1 = var1 + obj3.var1;
In the last statement, var1 belongs to the object that has called the operator function which in this case
is obj2.

Output:
Object 2
Enter value of data member var1 :- 10
Enter value of data member var2 :- 12

Object 3

Page 186 of 223


Enter value of data member var1 :- 11
Enter value of data member var2 :- 14

Object 1 after addition


Value of data member var1 :- 21
Value of data member var2 :- 26

Check your progress/ Self assessment questions- 2

Q6. How can you differentiate between the definition of pre and post increment operator functions?

Q7. How the function header of operator function for overloading binary operator is different from
function header of unary operator function?

13.5Summary
Operator overloading is a key concept of C++ programming. Operator overloading is a type of
polymorphism and is used to give new meaning or create multiple forms of operators already
available in programming language. Only the operators that are pre-defined by C++ compiler can be
overloaded. Overloading is done to give new meaning to these operators and operator overloading
cannot be used to create or define new operators. Overloading an operator is restricted to giving
additional meaning to the operator and you cannot change the behavioral attributes of the operator. By
behavioral attributes, we mean the precedence, associativity and syntax for the operator.
Operator overloading can be achieved with the help of a special function called the operator function.
The operator function has a function header, function body that can contain a return statement just like
any function in C++. The body of the operator function determines the operation to be performed by it
and it can be different from the normal behavior of that operator. Hence, it is the body of the operator
function that determines the new meaning of the operator.
Operator function for overloading unary operator does not have any argument in the argument list.
Definition of the pre increment operator function does not include any argument in the function

Page 187 of 223


header and definition of the post increment operator function mentions it in the argument list of
function header. In case of overloading binary operator, one object is passed as argument to the
operator function.

13.6 Glossary
Unary operator- Operator that performs operation on single operand.
Binary operator- Operator that perform operation on two operands.
Polymorphism- It is a key feature of OOP and it means something having many forms.
Operator function- Special member function of class used for operator overloading.
Function- Set of blocked statements to achieve some objective.

13.7 Answers to check your progress/self assessment questions


1. Following operators cannot be overloaded in C++
a. Scope resolution operator ::
b. Dot operator .
c. Conditional operator ?:
d. Pointer-to-member operator .*
e. Preprocessor #
f. sizeof()
2. Only the operators that are pre-defined by C++ compiler can be overloaded. Overloading is done to
give new meaning to these operators and operator overloading cannot be used to create or define new
operators.
3. The :: operator is used to perform scope resolution at compile time rather than evaluate the
expression. Also the expression used with :: operator are identifiers known to compiler and are not
any expressions or variables that represent some value.
4. Operator overloading can be achieved with the help of a special function called the operator
function. The body of the operator function determines the operation to be performed by overloaded
operator and it can be different from the normal behaviour of that operator. Following is the function
header of an operator function.
Return_Type operator Operator_Symbol ( Argument list )
5. Yes, single operator function works fine for both pre and post increment function call statements
but it fails to differentiate between the type of function call statement used.
6. Definition of the pre increment operator function does not include any argument in the function
header and definition of the post increment operator function mentions it in the argument list of
function header.
7. In case of overloading unary operator, no arguments were passed to the operator function. But in
case of overloading binary operator, one object is passed as argument to the operator function.

Page 188 of 223


13.8 References/ Suggested Readings
1. Balagurusamy, Object Oriented Programming with C++, 3rd Edition, Tata McGraw-Hill
Education, 2006.
2. Lafore R, Object Oriented Programming in C++, 4th Edition Waite Group, 2002.
3. R. S. Salaria, Mastering Object-Oriented Programming with C++, Salaria Publishing House.

13.9 Model questions


1. What is operator overloading? Whic operators can be overloaded in C++?
2. Which operators cannot be overloaded in C++ and why?
3. Write a program to overload post and pre increment operators.
4. What is an operator function? Write operator function to overload binary minus '-' operator.
5. Write a program to overload == operator.

Page 189 of 223


Lesson- 14 Virtual functions
Structure
14.0 Objective
14.1 Introduction
14.2 Late binding
14.3 Pointer to object of derived class
14.4 Virtual functions
14.4.1 Properties of virtual functions
14.5 Pure virtual functions
14.6Summary
14.7 Glossary
14.8 Answers to check your progress/self assessment questions
14.9 References/ Suggested Readings
14.10 Model questions

14.0 Objective
After studying this lesson, students will be able to:
1. Define the concept of late binding.
2. Discuss the use of polymorphism with pointers.
3. Explain the concept of virtual functions.
4. Implement virtual functions.
5. Describe the property of pure virtual function.

14.1 Introduction
In the last two lessons the concept of early binding has been discussed in great detail. This lesson
deals with the concept of late binding. Late binding is in reference to member functions of the class. It
is also a type of polymorphism and it can be implemented using pointers only. Complete details and
implementation are given in this lesson regarding the late binding. The technique used to implement
the concept of late binding is called virtual function. After reading this lesson, you will be able to
answer all about virtual function and its one variation called pure virtual function.

14.2 Late binding


Run time or late binding of member functions is also a type of polymorphism. Consider the following
example of inheritance to get better understanding of it:
class base
{
private:
// data members
public:
void show ( ) ;
Page 190 of 223
};
class derived: public base
{

Page 191 of 223


private:
// data members
public:
void show ( ) ;
};
As you can see, class "derived" is derived from the base class "base". Both the classes use member
function show ( ) with the same prototype. Because the two member functions; one in base class and
one in derived class have absolutely same function prototype, it is called function overriding and not
function overloading. You have already seen a solution to this problem in lesson number 11 of this
SLM itself. You may use the class resolution or scope resolution operator to explicitly specify the
binding of the member function with the function call statement in case of function overriding. This
type of binding of member function with the function call statement is called static binding or binding
at compile time.
It can still be bettered. C++ programming language provides you with a mechanism that does the
binding of member functions to specific function call statements when the program is running. This
type of polymorphism is called run time polymorphism and it can be applied only to the member
functions that are overridden during inheritance. It can be achieved with the help of virtual functions
that are discussed in detail later in this lesson.
It is only at the run time that correct instance of the member function is invoked against the
appropriate class object in consideration. Class object can be of the base class or the derived class.
This type of binding is done much later after the program has been compiled, and the selection of the
specific member function is done dynamically when the program is running. Dynamic or runtime
binding in C++ can only be achieved with the help of pointer objects.

14.3 Pointer to object of derived class


You can declare a pointer as object of the derived class. But mostly the pointer of base class object is
used in inheritance. It is because the pointer of base class type is type compatible. Type compatibility
means that the pointer of base class object can also be used as pointer to the derived class object.
Eventually a single pointer object of the base class can also be used to point to objects of all derived
classes. Isn't it interesting.
Consider that you have a base class "base" and a derived class "derived" which is derived from the
base class. If you declare a pointer of "base" class object, it can also be used to point to the object of
"derived" class.
Example,
base bobj;
derived dobj;
base *ptr;

Page 192 of 223


ptr = &dobj;
The last statement in C++ programming language is perfectly valid and allowed in which the pointer
of the base class is used to refer to object of derived class.
Even though the pointer object of a base class can be used to point to object of derived class, there are
few limitations on the access of class members such as:
1. Let us suppose that the member function of the derived class is overridden from the base class.
Even if you make the base class pointer object point to the object of derived class, member function of
the base class will always be executed when you call that member function. You cannot directly
access the class members of derived class.

Program 1
Base class pointer object pointing to derived class object and accessing the overridden member
function
// header files
# include < conio.h >
# include< iostream.h >
// definition of base class
class base
{
private:
int b ;
public:
base ( )
{
b = 0;
}
void display ( )
{
cout<<"\n display ( ) of the base class :- " ;
cout<<"\n value of data member b of base class :- " << b ;
}
};

// definition of derived class


class derived: public base
{
public:

Page 193 of 223


void display ( )
{
cout<<"\n display ( ) of the derived class :- " ;
}
};
void main ()
{
// object of base class
base bobj ;
base * ptr ;
// object of derived class
derived dobj ;
// assigning the location of object belonging to base class to the pointer of base class type
cout<<" \n Base class pointer pointing to object of base class " ;
ptr = &bobj ;
ptr->display ( ) ;
// assigning the location of object belonging to derived class to the pointer of base class type
cout<<" \n Base class pointer pointing to object of derived class " ;
ptr = &dobj ;
ptr->display ( ) ;
getch();
}

Output:
Base class pointer pointing to object of base class
display ( ) of the base class :-
value of data member b of base class :- 0
Base class pointer pointing to object of derived class
display ( ) of the base class :-
value of data member b of base class :- 0

Even when the location of object belonging to the derived class is assigned to pointer of base class,
member function of the base class is executed when you call the member function of derived class.
You can overcome this problem by type casting the base class pointer using the following statement:
((derived *)ptr)->display ( ) ;

Page 194 of 223


The statement above is a type casting statement. It is used to temporarily convert the type of pointer
from base class to derived class. If you run the program again using this type casted statement, desired
member function of the derived class will be executed.

2. You can use the pointer object of base class to only access the class members inherited from base
class by the derived class and not the original members belonging to the derived class.

Consider the following definition of base and derived classes:


class base
{
private:
int b ;
public:
base ( )
{
b = 0;
}
void display ( )
{
cout<<"\n display ( ) of the base class :- " ;
cout<<"\n value of data member b of base class :- " << b ;
}
};

// definition of derived class


class derived: public base
{
public:
void display ( )
{
cout<<"\n display ( ) of the derived class :- " ;
}
void count ( )
{
// function body
}
};

Page 195 of 223


The display ( ) member function in derived class is overridden from the base class and hence can be
accessed using the pointer object of base class pointing to object belonging to the derived class. But
the member function count ( ) of derived class does not exist in the base class and hence the same
cannot be accessed using the pointer of base class type pointing to object of derived class.

Check your progress/ Self assessment questions- 1

Q1. If two member functions; one in base class and one in derived class have absolutely same
function prototype, it is called _.

Q2. The mechanism that does the binding of member functions to specific function call statements
when the program is in execution is called binding.

Q3. The pointer of base class type is type .

Q4. What are the limitations of suing the base class pointer object to access the members of derived
class.

14.4 Virtual functions


Virtual function is a powerful feature of C++ programming language. One version of Polymorphism
means the objects from different classes are able to respond to same message, but in different forms.
Polymorphism much like abstraction has the ability to refer to objects without any reference to their
respective classes. It is how a pointer to single base class can refer to objects to multiple derived
classes. But you have already seen that there are problems faced when you try to access the members
of derived class object using the pointer of base class type. When you try to access the member
function of derived class, the member of base class is executed. It happened because the compiler
simply ignores the value of the pointer object and uses the type of the pointer object to bind the
member function at run time.
This problem and other problems listed in last section can be overcome using the concept of virtual
function. Virtual function concept is used when you define two member functions of the same
prototype in the base class and the derived class. In such cases, you make the member function of the
base class virtual by adding the keyword virtual ahead of its definition. Virtual keyword helps the
C++ compiler at run time to bind the appropriate function using the content of the pointer object

Page 196 of 223


rather than the type of the pointer object. Virtual function concept helps the base class pointer to
execute different instances of the virtual function in derived classes as well.

Program 2
To implement the concept of virtual function
// header files
# include < conio.h >
# include< iostream.h >
// definition of base class
class base
{
public:
virtual void same ( )
{
cout<<"\n same ( ) of the base class " ;
}
void different ( )
{
cout<<"\n different ( ) of the base class " ;
}
};

// definition of derived class


class derived: public base
{
public:
void same ( )
{
cout<<"\n same ( ) of the derived class " ;
}
void different ( )
{
cout<<"\n different ( ) of the derived class " ;
}
};
void main ()
{

Page 197 of 223


// object of base class
base bobj ;
base * ptr ;
// object of derived class
derived dobj ;
// assigning the location of object belonging to base class to the pointer of base class type
cout<<" \n Base class pointer pointing to object of base class " ;
ptr = &bobj ;
ptr->same ( ) ;
ptr->different ( ) ;
// assigning the location of object belonging to derived class to the pointer of base class type
cout<<" \n Base class pointer pointing to object of derived class " ;
ptr = &dobj ;
ptr->same ( ) ;
ptr->different ( ) ;
getch();
}

Output:
Base class pointer pointing to object of base class
same ( ) of the base class
different ( ) of the base class
Base class pointer pointing to object of derived class
same ( ) of the derived class
different ( ) of the base class

Last line of the output is of our concern. When the pointer object of the base class type is assigned the
address of the derived class object and the two member functions are called through the pointer object
using the following statements:
ptr = &dobj ;
ptr->same ( ) ;
ptr->different ( ) ;
The member function same ( ) of the derived class is executed but the member function different ( ) of
the base class is executed. It happened because only the member function same ( ) of the base class is
defined using the keyword virtual and not the member function different ( ).

14.4.1 Properties of virtual functions

Page 198 of 223


Following are some of the key properties of virtual functions in C++ programming language:
1. Virtual function cannot be any function. It is a member functions of a class.
2. You cannot make the virtual function as static member of the class.
3. You can implement the concept of virtual function with the help of pointer object only.
4. You can use a virtual member function of one class as friend of another class.
5. The prototype of the virtual function in the base class should be replicated as such in the derived
classes to take advantage of the concept of virtual functions. In other words, you need to implement
function overriding rather than function overloading.
6. You cannot make a constructor function of base as virtual, but you can make the destructor function
of the base class as virtual.
7. The virtual function must be defined in the base class. Only the declaration or prototype of virtual
function won't do. Also it is not mandatory to re-define the virtual function in the derived classes.

14.5 Pure virtual functions


One of the restrictions of using the base class pointer object to access the member functions belonging
to the derived class is that you can access only the class members inherited from base class by the
derived class and not the original members of the derived class. For example, if a member function
show ( ) is defined in the derived class and you want to access it using the pointer object of base class
type, the same function should also be defined in the base class.
But sometimes there may not be the need to define the same function in the base class. Then you can
define a virtual function in the base class that does not perform any task and acts as a placeholder.
Such a virtual function is called pure virtual function or a "do nothing" pure virtual function.
A pure virtual function is one that does not have any body because it is just a placeholder and is not
expected to do anything. You can define a pure virtual function as member function of the base class
using the following syntax:
virtual void Function_name ( ) = 0 ;

Check your progress/ Self assessment questions- 2

Q5. Explain the concept of virtual function and its usage.

Q6. List the properties of virtual function in regard to constructor, static function, friend function and
pointer variable.

Page 199 of 223


Q7. What is a pure virtual function and why is it used?

14.6 Summary
C++ programming language provides you with a mechanism that does the binding of member
functions to specific function call statements when the program is running. This type of
polymorphism is called run time polymorphism. . It can be achieved with the help of virtual functions.
Pointer of base class type is type compatible. Type compatibility means that the pointer of base class
object can also be used as pointer to the derived class object. Eventually a single pointer object of the
base class can also be used to point to objects of all derived classes.
Even if you make the base class pointer object point to the object of derived class, member function of
the base class will always be executed when you call that member function. You cannot directly
access the class members of derived class. Also, using the pointer object of base class you can only
access the class members inherited from base class by the derived class and not the original members
of the derived class.
Virtual function concept is used when you define two member functions of the same prototype in the
base class and the derived class. Virtual keyword helps the C++ compiler at run time to bind the
appropriate function using the content of the pointer object rather and not the type of the object
pointer.. Virtual function concept helps the base class pointer to execute different instances of the
virtual function in derived classes as well. A pure virtual function is one that does not have any body.
Base class pointer object can access the members of the derived class that are inherited from base
class and not the original members of the derived class. Sometimes there may not be the need to
define the same function in the base class and hence you use the pure virtual function instead of basic
virtual function.

14.7 Glossary
Virtual Function- A member function in the base class defined using the virtual keyword. You create
a virtual function because the same is re-defined in the derived classes and it allows the pointer of
base class to access the re-defined functions of derived class object.

Page 200 of 223


Pure virtual function- A virtual function having no body.
Pointer- A variable used to store the address of another variable or reference.
Inheritance- Mechanism of creating a new class using the features of existing class.
Late binding- Binding of member functions to appropriate function call statements using objects at
execution time.

14.8 Answers to check your progress/self assessment questions


1. function overriding.
2. runtime.
3. compatible.
4. Couple of limitations are:
a. Even if you make the base class pointer object point to the object of derived class, member function
of the base class will always be executed when you call that member function.
b. Using the pointer object of base class you can only access the class members inherited from base
class by the derived class and not the original members of the derived class.
5. Virtual function concept is used when you define two member functions of the same prototype in
the base class and the classes derived from it. Virtual keyword helps the C++ compiler at run time to
bind the appropriate function using the content of the pointer object and not the type of the object
pointer. Virtual function concept helps the base class pointer to execute different instances of the
virtual function in derived classes as well.
6.
a. You cannot make the virtual function of the base class as static member of the class.
b. You can implement the concept of virtual function with the help of pointer object only.
c. You can use a virtual member function of one class as friend of another class.
d. You cannot make a constructor function of base as virtual.
7. A pure virtual function is one that does not have any body. Base class pointer object can access the
members of the derived class that are inherited from base class and not the original members of the
derived class. Sometimes there may not be the need to define the same function in the base class and
hence you use the pure virtual function instead of basic virtual function.

14.9 References/ Suggested Readings


1. Balagurusamy, Object Oriented Programming with C++, 3rd Edition, Tata McGraw-Hill
Education, 2006.
2. Lafore R, Object Oriented Programming in C++, 4th Edition Waite Group, 2002.
3. R. S. Salaria, Mastering Object-Oriented Programming with C++, Salaria Publishing House.

14.10 Model questions

Page 201 of 223


1. Explain the concept of late binding.
2. List various properties of virtual functions.
3. What is a pure virtual function and why you need to create one?
4. Explain the concept of virtual function with the help of a program.
5. How can you access member function of derived class using the pointer of base class object
without using virtual function? Explain with the help of a program.

Page 202 of 223


Lesson- 15 I/O Streams
Structure
15.0 Objective
15.1 Introduction
15.2 Streams
15.3 Stream classes
15.4 Header files
15.5 Buffer
15.6 Redirection
15.7 Summary
15.8 Glossary
15.9 Answers to check your progress/self assessment questions
15.10 References/ Suggested Readings
15.11 Model questions

15.0 Objective
After studying this lesson, students will be able to:
1. Define the concept of streams in C++.
2. Explain the role of various stream classes in C++.
3. List various header files used to perform input and output operations in C++.
4. Describe the usage of buffer.
5. Discuss the importance of redirection in C++.

15.1 Introduction
All programs written using any programming language start by accepting input from the user. Then
after processing the input, output is displayed to the user. So as a programmer, one must known how
the input and output works in a specific programming language. For every programming language,
input is provided using a default input source which normally is a Keyboard and output is provided to
a default output source which normally is monitor. In C++ programming language input is provided
using cin with operator >> and output using cout with << operator. In this lesson, you will learn the
concept of stream classes that are responsible for the input and output operation in C++ programming
language. You will also see how you can change the default input and output source to work with
other sources. I am sure you will have great time studying this lesson and learn a lot about how input
and output works in C++.

15.2 Streams
C++ provides its programmers a number of functions to perform Input/ Output operations that makes
use of the concepts like classes, inheritance and virtual functions. So it is important that you
understand these concepts before you start with the I/O operations. I/O operations can be performed
Page 203 of 223
with the console ( i.e. input and output devices ) or with the files. I/O operations in C++ are performed
with the help of streams and stream classes.
You can work with a wide range of I/O devices using the C++ programming language. All these
devices are quite different from each other, but the I/O system of C++ provides an interface to the
programmers that is independent of the type of device being used.
A stream in simple words is a sequence of words. Input stream is one that acts as a source from where
the data is obtained and an output stream is one that acts as a destination where the data is sent.

Page 204 of 223


Figure 15.1 Input and Output streams in C++

The default input stream is keyboard and the default output stream is monitor. The input and output
streams can also be redirected to any storage device. You must be familiar with cin and cout, two
streams used in C++ programs to perform input and output operations.

15.3 Stream classes

Figure 15.2 Hierarchy of stream classes in C++

The I/O system of C++ programming language is a hierarchy of classes called stream classes.
Hierarchy because they implement the concept of inheritance. These classes are used to perform the
input and output operation on both the console and the disk. Stream class ios is the base class for all
other classes or you can say at the top of the hierarchy. Stream classes istream, streambuf and ostream
are directly inherited from the base class ios. The istream and ostream are then further derived by the
stream class iostream. The streambuf class is derivedby stringbuf and filebuf.
These classes provide support for both the formatted and the unformatted input and output operations.

Following are some of the operators and functions used to provide unformatted I/O operations

Page 205 of 223


1. You have already seen the use of cin and cout to perform input and output operations respectively.
Both of these are the objects of iostream class. Operator >> is overloaded in the istream class and
operator << is overloaded in the ostream class to support input and output operations.

2. put ( ) is a member function of class ostream and is used to write a character on the output stream,
whereas get ( ) is a member function of class istream and is used to read a character from the input
stream. You can use the get ( ) and put ( ) member functions using the cin and cout objects of istream
and ostream classes respectively as follows:
cin.get ( ch ) ; // it is used to read a character from keyboard and assign the same to ch.
cout.put ( ch ) ; // it is used to write a content of variable ch on the monitor.

3. getline ( ) is used to read a complete line terminated by new line character from the input stream,
whereas write ( ) is used to write a series of characters on the output stream. The getline ( ) function
can be invoked using the cin object of class istream as follows:
cin.getline ( name , 20 ) ; // name is a string and 20 is the size. Only 19 characters at max can be read
If new line character is encountered before 19 characters, the input will terminate there.
The write ( ) function can be invoked using the cout object of class ostream as follows:
cout.write ( name , 20 ) ; // name is a string and 20 is the size.

Formatted I/O operations


Formatted I/O operations can be performed in C++ programming language using member functions
and flags of ios class or manipulators.
Some of the member functions of ios stream class that can be used to perform the formatted I/O
operations are as follows:
width ( ) - It is used to specify the requirement of field size to display an output value.
precision ( )- It is used to specify the number of digits that should be displayed on output stream
after the decimal point when displaying a float value.
fill ( )- It is used to specify a character that will be used to fill the portion that is unused in
the field.
setf ( )- It is used to specify various format flags like, left-justify or right-justify used to
control the way output is displayed on the output stream.
unsetf ( )- It is used to clear the specific flags set using the sef ( ).

Manipulator functions are prototyped in the iomanip.h header file and hence the same should be
included to make use of them. Manipulators in C++ are built-in functions that can be used with I/O
statements to alter the parameters of the stream.
Following are some of the manipulators and their equivalent member functions of ios stream:

Page 206 of 223


setw ( ) width ( )
setprecision ( ) precision ( )
setfill ( ) fill ( )
setiosflags ( ) setf ( )
resetiosflags ( ) unsetf ( )

Check your progress/ Self assessment questions- 1

Q1. A stream in simple words is a of words.

Q2. Input stream acts a from where the data is obtained and an output stream acts as
a where the data is sent.

Q3. The default input stream is and the default output stream is .

Q4. Explain the objective of get ( ) and put ( )?

Q5. What is the width ( ) and precision ( ) manipulators?

15.4 Header files


In order to make use of I/O stream classes in C++ programs, you have to include the header files that
contain the prototypes of the classes you want to use. You can perform the read and write operation
using the console and the disk. Following are the four header files that you may need to perform the
I/O operation in C++ programming language:
# include < iostream.h >
# include <fstream.h >
# include < iomanip.h >
# include < string.h >

To perform standard input and output operations using the cin and cout objects of istream and ostream
classes, you need to include the "iostream.h" header file. "fstream.h" header file is used when you

Page 207 of 223


want to perform input and output operations on the files. It includes the prototypes of fstream,
ifstream and ofstream classes. If you want to use the manipulator functions listed in the last section
that are used to perform the formatted input and output operations, you need the header file
"iomanip.h" which stands for I/O manipulators. "string.h" header file is used if you want to make use
of any string related built-in functions.

15.5 Buffer
Whatever data is sent to the output stream is not always printed at the same time. There are a number
of reasons for the delay and the data sent to the output stream is often kept in temporary storage called
the stream buffer. Once the event occurs for which the delay was caused, the data is sent from the
stream buffer to the output stream. The same applies to the input stream as well.
A stream buffer is always associated with a stream object ( irrespective of whether the stream object is
buffered or un-buffered ) and it is the one responsible for performing both the read and write
operations of the associated stream object. Stream buffer object acts as an interface between the
stream and its controlled I/O sequences and all read and write operations are delegated to it by the
stream. A Stream buffer type for the stream objects is set to either make use an intermediate buffer or
not.
Flushing is a term associated with buffer and often used in C++ programming. Flushing is basically
used to make all the output that has been buffered in temporary space to be sent for printing at once. It
is also known as flushing the stream. Flushing is also useful when you accept input of strings from the
default device. Flushing can be achieved by using the function flush, or inserting the keyword flush or
endl to the output stream. A stream buffer object maintains a locale object for locale-dependent
operations, a set of pointers used to maintain the input buffer ( eback , egptr , gptr ) and set of pointers
used to maintain the output buffer ( epptr , pbase , pptr ).

Figure 15.3 Streambuf Class

The streambuf class is derived by the filebuf and stringbuf classes and it provides uniform interface
for all derived classes: This interface is used to call the virtual members that derived classes may

Page 208 of 223


override to implement specific behaviour. These overridden virtual functions have the access to
streambuf class internals using the protected functions.

15.6 Redirection
The input and output in the C++ programming language is done using the standard input and standard
output. It means that the source of input for any command is the standard input device which by
default is keyboard and also the standard source of output by default is monitor. Input and output in
C++ is done using the cin and cout and some other pre-defined functions. Redirection is an interesting
and very powerful feature of C++. C++ programming language lets you switch from the standard
stream and accept data input from sources other than the default source and also redirect to some other
output source than the standard output source.
The most popular redirection is to accept input or make some file as the standard input source and
also some file can be made the default output source. Also some other program can be made the
default input source which means that a program accepts its input from some other source rather than
directly getting the input from the default source like keyboard.
Not just the outputs, but error messages also have a standard output source. Even printers are a widely
used standard output source when performing redirection.
It is not advisable to change the default source of input and output devices. Once as a programmer you
have made use of redirection and changed the standard input and output devices for some times, it is
however appropriate to restore the original devices once you are finished with it.

Check your progress/ Self assessment questions- 2

Q6. List various header files that you may need to perform I/O operation in C++.

Q7. What is a stream buffer?

Q8. Explain the concept of redirection.

Page 209 of 223


Q9. What is flushing?

15.7 Summary
You can work with a wide range of independent I/O devices and C++ provides an interface to the
programmers that is independent of the type of device being used. A stream is a sequence of words.
Input stream is one that acts a source from where the data is obtained and an output stream is one that
acts as a destination where the data is sent. The default input stream is keyboard and the default output
stream is monitor. The I/O system of C++ programming language is a hierarchy of classes called
stream classes responsible for performing I/O operations.
Operator >> is overloaded in the istream class and operator << is overloaded in the ostream class to
support unformatted input and output operations. put ( ) is a member function of class ostream and is
used to write a character on the output stream, whereas get ( ) is a member function of class istream
and is used to read a character a from the input stream. getline ( ) is used to read a complete line
terminated by new line character from the input stream, whereas write ( ) used to write a series of
characters on the output stream.
Some of the member functions of ios stream class used to perform the formatted I/O operations are
width ( ), precision ( ), fill ( ), setf ( ) and unsetf ( ). Some of the manipulators used to perform the
formatted I/O are setw ( ), setprecision ( ), setfill ( ), setiosflags ( ) and resetiosflags ( ). Header files
needed to perform the I/O operation in C++ programming are iostream, fstream, iomanip and string.
Sometimes the data sent to the output is kept in temporary storage called the stream buffer. A stream
buffer is always associated with a stream object and is responsible for performing both the read and
write operations of the associated stream object. Stream buffer object acts as an interface between the
stream and its controlled I/O sequences and all read and write operations are delegated to it by the
stream.
The input and output in the C++ programming language is done using the standard input and standard
output sources. By default, the standard input device is keyboard and standard output device is
monitor. Redirection lets you switch from the standard stream and accept data input from sources
other than the default source and also redirect to some other output source than the standard output
source.

15.8 Glossary
Redirection- It lets you switch from the standard stream and accept data input from sources other than
the default source and also redirect to some other output source than the standard output source.

Page 210 of 223


Stream buffer- Sometimes the data sent to the output is kept in temporary storage called the stream
buffer. A stream buffer is responsible for performing both the read and write operations of the
associated stream object.
Stream- It is a sequence of bytes
Flushing- It is basically used to make all the data sent to output stream that has been buffered in
temporary space called stream buffer.

15.9 Answers to check your progress/self assessment questions


1. sequence.
2. source , destination.
3. keyboard , monitor.
4. put ( ) is a member function of class ostream and is used to write a character on the output stream,
whereas get ( ) is a member function of class istream and is used to read a character a from the input
stream.
cin.get ( ch ) ;
cout.put ( ch ) ;
5.
a. width ( ) is used to specify the requirement of field size to display an output value.
b. precision ( ) is used to specify the number of digits that should be displayed on output stream after
the decimal point when displaying a float value.
6. Following are the four header files needed to perform the I/O operation in C++ programming
language:
 iostream
 fstream
 iomanip
 string

7. Sometimes the data sent to the output is kept in temporary storage called the stream buffer. A
stream buffer is always associated with a stream object and is responsible for performing both the
read and write operations of the associated stream object. Stream buffer object acts as an interface
between the stream and its controlled I/O sequences and all read and write operations are delegated to
it by the stream.

8. The input and output in the C++ programming language is done using the standard input and
standard output sources. By default the standard input device is keyboard and standard output device
is monitor. Redirection lets you switch from the standard stream and accept data input from sources

Page 211 of 223


other than the default source and also redirect to some other output source than the standard output
source.

9. Flushing is basically used to make all the output that has been buffered in temporary space to be
sent for printing at once. It is also known as flushing the stream. Flushing can be achieved by using
the function flush, or inserting the keyword flush or endl to the output stream.

15.10 References/ Suggested Readings


1. Balagurusamy, Object Oriented Programming with C++, 3rd Edition, Tata McGraw-Hill
Education, 2006.
2. Lafore R, Object Oriented Programming in C++, 4th Edition Waite Group, 2002.
3. R. S. Salaria, Mastering Object-Oriented Programming with C++, Salaria Publishing House.

15.11 Model questions


1. What is the objective of redirection in C++ programming language?
2. Explain the usage of various stream classes with the help of diagram?
3. What is a stream buffer? Explain in detail.
4. What is a stream and what is its role in I/O operations.
5. Explain all functions and operators used to perform formatted and unformatted I/O.

Page 212 of 223


Lesson- 16 File Handling
Structure of the lesson
16.0 Objective
16.1 Introduction
16.2 Files in C++
16.3 File stream classes
16.4 Opening and closing of files
16.5 Input/ Output member functions of file stream class
16.6 Summary
16.7 Glossary
16.8 Answers to check your progress/self assessment questions
16.9 References/ Suggested Readings
16.10 Model Questions

16.0 Objective
Objective of this lesson is to help the student understand the following:
1. Describe the types of files you can work with in C++.
2. Explain the role of various classes involved in creation and updataion of files and their individual
roles.
3. State various modes for opening a file.
4. Re-write programs to perform read and write operations on files.

16.1 Introduction
Storing of data permanently on the secondary disk is vital feature of any programming language.
Large amount of data is generated on daily basis that needs to be recorded for future retrieval. There is
no point in making programs if you cannot save the data on disk and the data is lost after the programs
execution is terminated. Using C++ file concept, you can save data permanently on the disk in the
form of structure of files. A file is a collection of bytes stored on disk. Programs are written in C++ to
perform read/write operations on these files. File in C++ can be created as a text or binary file and you
can access the data in the file randomly. C++ also allows you to write the structures and classes
directly to the files in addition to writing simple text. C++ lets you check for various error conditions
when working with files that help you create effective programs. C++ provides you with a number of
in-built functions used to perform read, write and error checking functions.

16.2 Files in C++

As already stated that a file in C++ is used to store data permanently on secondary disk. In C++
programming language, you can create and use two different types of files. A text file is a sequence of

Page 213 of 223


characters. You can access each character individually or a group of characters together. You can
insert text, delete or even append text to the end of the file. Text file is processed sequentially. Binary
file is almost similar to a text file and it is a collection of bytes. There is one difference between text
and binary file. No processing is needed when you copy a binary file and it can be processed
sequentially and randomly as well. File created using binary mode can even read characters like
newline which are hidden in text mode.

16.3 File stream classes


C++ provides you with built-in classes for handling files. The main class is fstreambase and three
classes are further derived from it; ifstream, ofstream and fstream. File handling classes are derived
from the base class named fstreambase and from the parallel iostreamclass. Header file fstream.h
consists of all classes designed to manage the disk files.

16.4 Opening and closing of files


You must include the header file "fstream.h" to your program if you want to work with files. Once
you have included the "fstream.h" header file to your program, you need to create an object of one of
the three file stream classes named fstream, ifstream or ofstream.
You can open a file for reading either using the constructor function or by using the member function
open ( ) of the file stream classes.

Constructor is a special member function of the class which is automatically called for execution
when the object of the same is created. You can access the file once it is opened using the object of
file class stream. To open a file using constructor function, a valid name of the file is passed as
argument to the constructor function. Choice of file stream class is based on the operation to be
performed. Object of class ofstream is created if you need to use output stream only for writing to the
file, object of class ifstream is created if you need to use the input stream only for reading from the
file. Object of fstream class is created when you want to use both the output and input streams for
reading and writing into the file simultaneously.
You can open a file by creating object using either of three statements given below:
ifstream fileobj ( "sample.txt" ) ;
This statement is used to create an object of ifstream and open a file named "sample.txt" for only the
read operation.
ofstream fileobj ( "sample.txt" ) ;
This statement is used to create an object of ofstream and open a file named "sample.txt" for only the
write operation.
fstream fileobj ( "sample.txt" ) ;
This statement is used to create an object of fstream and open a file named "sample.txt" for both the
read and write operations.

Page 214 of 223


Open ( ) member function of the file stream classes can also be used to open a file. When you declare
an object of the file stream class and do not pass any file name as argument, object is created without
opening any file. You can then use the open ( ) member function to open a file.
Syntax to open a file using open ( ) is,
Object_Name . open ( File_Name , mode ) ;

Object_Name refers to the name of file stream class object. You can open a file using various file
opening modes depending upon the type of operation that you want to perform. The open ( ) member
function is overloaded. The mode parameter is optional. You can also call the open ( ) by passing
single argument, i.e. name of the file to be opened.
In case the file does not open successfully, the object of file stream class is assigned NULL value.

Some of the file opening modes are as follows:


ios::in It is used to open a file to perform only the input operation.
ios::out It is used to open a file to perform only the output operation.
ios::ate It is used to open a file and position the pointer to the end of file.
ios::app It is used to open a file to perform the output operation and position the pointer to the
end of file appending the content of the file.
ios::binary It is used when you want to perform operations on a file using binary mode rather
than text mode.
If you call the open ( ) member function and pass only the file name; then depending on the file
stream class the file object belongs to, a default file opening mode is set.
ofstream ios::out
ifstream ios::in
fstream ios::in | ios::out

Check your progress/ Self assessment questions- 1


Q1. What are the differences between text file and binary file in C++?

Q2. You must include the header file to your program if you want to work with
files.

Q3. You cannot open a file using constructor function of file stream class. (TRUE/ FALSE)

Q4. What is the purpose of ios::binary and ios::app modes?

Page 215 of 223


Q5. List the default modes set for opening a file for the fstream, ifstream and ofstream classes?

close ( ) member function of the file stream class is used to close the file and stop any operations on
that file using the object of the file stream class. File is automatically closed when the program
terminates. You can also close the connection of the object with file during the program execution by
calling the close ( ) member function. It is useful if you want to open a new file using the same object
or you want to close the file and open it for some other operation or open it using some other mode.
Syntax to close a file using close ( ) is,
Object_Name . close ( ) ;
The object still remains and it can be used to open another file.

Program 1
To open the file using open ( ) and also close it using close ( ) the file

// header files
# include < iostream.h >
# include < fstream.h >
# include < conio.h >
void main ( )
{
//object of fstream class
fstream objfile;
// opening the file
objfile.open ( "sample.txt , ios::out " ) ;
if ( objfile == NULL) // file did not open
{
cout<<" \n The file failed to open and the program will terminate now! " ;
getch ( ) ;
return ; // to terminate the program execution
}
else
{
cout<<" \n The file opened successfully " ;
getch();

Page 216 of 223


}
cout<< " \n Closing the file now " ;
objfile.close ( ) ;
getch ( ) ;
}

Program 2
To perform write and read operations on a file using << and >> operators
// header files
# include < iostream.h >
# include < fstream.h >
# include < conio.h >

void main ( )
{
char ch[ 50 ] ;
//object of fstream class
fstream objfile;
// opening the file to perform write operation
objfile.open ( "sample.txt , ios:: out " ) ;
if ( objfile == NULL) // file did not open
{
cout<<" \n The file failed to open and the program will terminate now! " ;
getch ( ) ;
return ; // to terminate the program execution
}
// write operation on the file using << operator
objfile<<"IKGPTU" ;
cout<<" \n IKGPTU written to the file ” ;
getch();
// closing the file
objfile.close ( ) ;
// opening the file to perform read operation
objfile.open ( "sample.txt" ) ;
if ( objfile == NULL) // file did not open
{

Page 217 of 223


cout<<" \n The file failed to open and the program will terminate now! " ;
getch ( ) ;
return ; // to terminate the program execution
}
// read operation on the file using >> operator
cout<< " \n Reading data from the file " ;
objfile>>ch;
cout<<” \n ” << ch ;
getch();
}

Output:
IKGPTU written to the file
Reading data from the file
IKGPTU

Check your progress/ Self assessment questions- 2


Q6. File is automatically closed when the program terminates. (TRUE/ FALSE)

Q7. You can also close the connection of the object with file during the program execution by calling
the member function of file stream class.

16.5 Input/ Output member functions of file stream class


Read and write operation on files using C++ is made easy with the help of built-in member functions
of file stream classes. Before you learn the basic input/ output functions used to read and write data on
files, it is important that you understand the end of file (EOF) condition. Read operation is performed
sequentially on the file. Knowing that you have reached the end of file is vital. It helps to prevent the
program from reading the file once you reached the end of file.
C++ file stream classes contain a member function called eof ( ) used to check whether or not the end
of file has been reached.
Syntax of using the eof ( ) member function:
File_Object . eof ( ) ;
It returns TRUE, if the end of file has been reached for the file connected to file stream class object,
and it returns FALSE, if the end of file has not been reached for the same file.

Page 218 of 223


C++ provides a number of member function to perform the read and write operations on file. In this
section you will learn only two member functions, one used to write data into the file and other used
to read data from the file.
put ( ) member function of the file stream class is used to write one character at a time into the file and
get ( ) member function is used to read one character at a time from the file. There are other functions
that allow you to read and write a full string into the file and also read and write class and structure
objects into the file.
Syntax to perform the write operation on file using the put ( ) member function:
File_Object . put ( char ) ;

Syntax to perform the read operation on file using the get ( ) member function:
File_Object . get ( char ) ;

Program 3
To perform read and write operation on a file using get ( ) and put ( ) member functions
// header files
# include < iostream.h >
# include < fstream.h >
# include < conio.h >
void main ( )
{
//object of fstream class
fstream objfile ;
char ch [ 50 ] = {"Welcome to IK Gujral Punjab Technical University"} ;
char c ;
int count;
// opening the file to perform write operation
objfile.open ( "sample.txt" , ios::out ) ;
if ( objfile == NULL) // file did not open
{
cout<<" \n The file failed to open and the program will terminate now! " ;
getch ( ) ;
return ; // to terminate the program execution
}
// write operation on the file using put ( ) member function
cout<<" \n Performing the write operation on file " ;
for ( count = 0 ; ch [ count ] != '\0' ; count++ )

Page 219 of 223


{
objfile.put ( ch [ count ] ) ;
}
cout<<" \n Welcome to IK Gujral Punjab Technical University written to the file " ;
//closing the file
objfile.close ( ) ;

// opening the file to perform read operation


objfile.open ( "sample.txt" , ios::in ) ;
if ( objfile == NULL) // file did not open
{
cout<<" \n The file failed to open and the program will terminate now! " ;
getch ( ) ;
return ; // to terminate the program execution
}
// read operation on the file using get ( )
cout<<"\n Reading data from the file " ;
cout<<" \n " ;
while ( ! ( objfile.eof ( ) ) )
{
objfile.get ( c ) ;
cout<<c ;
}
//closing the file
objfile.close ( ) ;
getch();
}

Output:
Performing the write operation on file
Welcome to IK Gujral Punjab Technical University written to the file
Reading data from the file
Welcome to IK Gujral Punjab Technical University

Check your progress/ Self assessment questions- 3


Q8. Why it is important to detect the end of file and how can you detect it in C++?

Page 220 of 223


Q9. What is the role of put ( ) and get ( ) member functions file stream classes?

16.6 Summary
File in C++ is used to store data permanently on secondary disk. In C++ programming language, you
can create and use two different types of files. A text file is a sequence of characters. You can access
each character individually or a group of characters together. Text file is processed sequentially.
Binary file is a collection of bytes. No processing is needed when you copy a binary file and it can be
processed sequentially and randomly as well. File created using binary mode can even read characters
like newline which are hidden in text mode.
"ifstream" is a file stream class used to perform only the input operations on the file, "ofstream" is a
file stream class used to perform only the output operations on the file and "fstream" is a file stream
class used to perform both the input and the output operations on the file. You must include the header
file "fstream.h" to your program if you want to work with files and then you need to create an object
of one of the three file stream classes. You can open a file for reading either using the constructor
function or by using the member function open ( ) of the file stream classes. Syntax to open a file
using open ( ) is,
Object_Name . open ( File_Name , mode ) ;
Some of the file opening modes are as follows:
ios::in
ios::out
ios::ate
ios::app
ios::binary
Default file opening modes for the three file stream classes are as follows:
ofstream ios::out
ifstream ios::in
fstream ios::in | ios::out
close ( ) member function of the file stream class is used to close the file and stop any operations on
that file using the object of the file stream class. C++ file stream classes contain a member function
called eof ( ) used to check whether or not the end of file has been reached. It returns TRUE, if the
end of file has been reached for the file connected to file stream class object, and it returns FALSE, if

Page 221 of 223


the end of file has not been reached for the same file. put ( ) member function of the file stream class
is used to write one character at a time into the file and get ( ) member function is used to read one
character at a time from the file.

16.7 Glossary
File- file in C++ is used to store data permanently on secondary disk.
Text file- A text file is a sequence of characters that are processed sequentially.
Binary file- Binary file is a collection of bytes that can be processed sequentially and randomly. File
created using binary mode can even read characters like newline which are hidden in text mode.
Ifstream- It is a file stream class used to perform only the input operations on the file.
Ofstream- It is a file stream class used to perform only the output operations on the file.
Fstream- It is a file stream class used to perform both the input and the output operations on the file.
put()- Member function of file stream class used to write a single character to a file.
get()- Member function of file stream class used to read a single character from a file.
eof ( )- Member function of file stream class used to check if the end of file has been reached or not.

16.8 Answers to check your progress/self assessment questions


1. Text file is processed sequentially and a binary can be processed sequentially and randomly as well.
File created using binary mode can even read characters like newline which are hidden in text mode.
2. fstream.h.
3. FALSE.
4. ios::app mode is used to open a file to perform the output operation and it positions the pointer to
the end of file appending the existing content of the file. ios::binary mode is used when you want to
perform operations on a file using binary mode rather than text mode.
5. Default file opening mode for the three file stream classes are as follows:
ofstream ios::out
ifstream ios::in
fstream ios::in | ios::out
6. TRUE.
7. close ( ).
8. Read operation is performed sequentially on the file. Knowing that you have reached the end of file
helps to prevent the program from reading the file once you reached the end of file. C++ file stream
classes contain a member function called eof ( ) used to check whether or not the end of file has been
reached. It returns TRUE, if the end of file has been reached, and it returns FALSE, if the end of file
has not been reached.
9. put ( ) member function of the file stream class is used to write one character at a time into the file
and get ( ) member function is used to read one character at a time from the file.

Page 222 of 223


16.9 References/ Suggested Readings
1. Balagurusamy, Object Oriented Programming with C++, 3rd Edition, Tata McGraw-Hill
Education, 2006.
2. Lafore R, Object Oriented Programming in C++, 4th Edition Waite Group, 2002.
3. R. S. Salaria, Mastering Object-Oriented Programming with C++, Salaria Publishing House.

16.10 Model Questions


1. Write a program to write and read data to and from the file respectively using put ( ) and get ( ).
2. Explain various modes used to open a file in C++.
3. Explain the differences between the text and the binary files.
4. Explain the two methods for opening a file in C++.

Page 223 of 223

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy