133805901735423145
133805901735423145
133805901735423145
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)
Written by:
Seema Gupta, Assistant Professor,
Mayur College, Kapurthala
Reviewed by:
Dr.Vinay Chopra,
Asssitant Professor, DAVIET, Jalandhar
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.
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.
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.
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.
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 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.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.
() Function call
2 [] Array subscripting
3 * Indirection (dereference)
& Address-of
sizeof Size-of
Page 6 of 223
12 | Bitwise OR (inclusive or)
14 || Logical OR
17 , Comma Left-to-right
Page 7 of 223
Q8. All concepts of OOP's can only be realized in C++ with the help of data type.
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;
}
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.
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.
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.
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 ).
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.
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.
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
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.
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
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.
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.
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?
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.
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".
Q12. You can access each member using the they belong to..
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.
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.
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.
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
Q1. Each elements in the array of structure objects share the same and is accessed
individually using its number.
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
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
Q5. You can access the member of nested structure using dot operator.
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.
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.
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.
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.
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.
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.
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 )
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 ( ) ;
};
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.
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.
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.
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.
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.
// 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.
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.
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.
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
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.
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.
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.
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.
Q9. You create a private member function so that it can be called or accessed using a
of the same class.
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.
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.
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.
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
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.
Program 2
To create an array of class objects
// header files
#include<conio.h>
#include<iostream.h>
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
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
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?
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
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
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.
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.
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:
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.
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();
}
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.
Q4. Objective of the constructor function is to the data members of the class.
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();
}
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
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.
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();
}
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;
}
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.
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.
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
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.
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
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.
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.
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)
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 ( ) ;
};
AREA::AREA ( )
{
area = 0 ;
}
void AREA::compute ( rectangle r2 )
{
area = r2.length * r2. breadth;
}
void AREA::display ( )
{
cout<<" \n Area of rectangle is :- " << area ;
}
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)
Program 3
Making a function friend function of two classes
// header files
# include< conio.h >
# include < iostream.h >
// prototype of class square
class square ;
{
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 ;
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 ( ) ;
}
{
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:
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
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.
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.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.
//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. " ;
}
};
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.
PROGRAM 2
Attendance marking using static data member
// header files
# include <conio.h>
# include <iostream.h>
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 ;
//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 " ;
Q4. The normal data members of a given class can be accessed using a operator with
name to which they belong.
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 .
//header files
# include < iostream.h >
# include < conio.h >
//definition of class
class ACTIVE
{
Q8. Which all data members can be accessed using static member function?
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.
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.
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.
Q5. Multiple inheritance can have multiple levels of inheritance. ( TRUE / FALSE )
Q13. How defining a derived class is different from defining a simple class?
Q15. The inheritance mode in definition of derived class is optional ( TRUE / FALSE )
Q16. Inheritance mode can take one of the three values; , and
.
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
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.
11.0 Objective
After studying this lesson, students will be able to:
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.
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)
// header files
# include< conio.h >
#include< iostream.h >
public:
void input_details ( )
{
void display_details ( )
{
cout<<"\nStudents name :- "<<name;
cout<<"\nStudents class:- "<<class_no;
cout<<"\nStudents Roll number:- "<<roll_no;
}
};
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()
{
void main ()
{
// object of derived class marks
marks obj1;
int avg;
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
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>
public:
void input ( )
{
cout<<"Enter the students name :- ";
cin>>name;
void display ( )
{
cout<<"\nStudents name :- "<<name;
cout<<"\nStudents class:- "<<class_no;
cout<<"\nStudents Roll number:- "<<roll_no;
}
};
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;
}
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 ()
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?
Program 3
To implement multilevel inheritance
// header files
#include<iostream.h>
#include<conio.h>
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
Output:
Roll number of the student is :- 12
Marks in math :- 75
Marks in science :- 85
Average marks = 80
Program 4
To demonstrate the calling of constructor's in case of multilevel inheritance
// header files
#include<conio.h>
#include<iostream.h>
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
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>
void main ()
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.
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
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 .
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.
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.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.
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 .
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
Q6. If the integral promotion also does not work, then the compiler tries the
to the actual arguments.
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 )
{
{
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;
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;
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 )
{
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 ;
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
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
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 ;
}
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.
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.
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.
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:
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++.
Q2. Which operators can be overloaded and what is the objective of overloading operators in C++?
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
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;
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;
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:
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( )
{
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;
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.
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 ( )
{
void main( )
{
// objects of class INC
INC obj1, obj2;
cout<<”\nObject 1”;
//call to memebr function of obj1
obj1.input( );
Output:
Object 1
Enter value of data member var1 :- 10
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>
void main( )
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
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
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.
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.
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 ;
}
};
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 ( ) ;
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.
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.
Q4. What are the limitations of suing the base class pointer object to access the members of derived
class.
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 " ;
}
};
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 ( ).
Q6. List the properties of virtual function in regard to constructor, static function, friend function and
pointer variable.
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.
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.
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.
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
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.
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:
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 .
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
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 ).
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
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.
Q6. List various header files that you may need to perform I/O operation in C++.
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.
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
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.
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.
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
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.
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.
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)
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();
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
{
Output:
IKGPTU written to the file
Reading data from the file
IKGPTU
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.
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++ )
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
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
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.