0% found this document useful (0 votes)
458 views

OOPS-Paradigm Using C++ Final

The document discusses object-oriented programming concepts and C++ programming. It covers topics like introduction to OOP, history of C++, standard libraries, basic input/output, variables, data types, and more. C++ was developed in the early 1980s by Bjarne Stroustrup at AT&T Bell Laboratories.

Uploaded by

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

OOPS-Paradigm Using C++ Final

The document discusses object-oriented programming concepts and C++ programming. It covers topics like introduction to OOP, history of C++, standard libraries, basic input/output, variables, data types, and more. C++ was developed in the early 1980s by Bjarne Stroustrup at AT&T Bell Laboratories.

Uploaded by

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

Chapter 1

Object Oriented
Programing Concept

1.1 INTRODUCTION

Object-Oriented Programming means a programming approach based


on objects and classes. The object-oriented concept allows us to organize software as
a collection of objects that consist of both data and behavior.
It is widely accepted that object-oriented programming is the most important and
powerful way of creating software. This is in contrast to conventional functional
programming in which data is global and insecure.
Objects came in the real world in the 1980s. Basically it contains data in the form of
attributes and executable code in the form of functions called methods. It is not
restricted to say that the object itself is a basic concept of object-oriented
programming.

The object-oriented programming approach encourages

Module based programming where the application can be decomposed into modules
and modules can be correlated with classes of high level and real world and reuse of
software where an application can be composed from existing and new modules.
Various most widely used languages which come under the category of OOPs are: C++,
C#, Java, Python, Ruby, et cetera.
1.2 HISTORY OF C++

C++ was initially named ‘C with Classes’. C++ was developed by Bjarne Stroustrup at
AT & T Bell laboratories in Murry Hill, New Jersey, USA, in the early 1980’s.

Year Language Developed by About language

1960 ALGOL International Committee Too general, Too abstract


Hard to learn, Difficult to
1963 CPL Cambridge University
implement
Could deal with only specific
1967 BCPL Martin Richards
problems
Ken Thompson at AT & T Could deal with only specific
1970 B
Bell Labs problems
Dennis Ritchie at AT & T Lost generality of BCPL and
1972 C
Bell Labs B restored
Early
C++ Bjarne Stroustrup at AT & T Introducing OOPs.
80’s
C++ was initially named ‘C with Classes’.
C++ was developed by Bjarne Stroustrup at AT & T Bell laboratories in Murry Hill,
New Jersey, USA, in the early 1980’s.
C++ is an Object Oriented Language but not a pure Object Oriented Language because
in C++ even without using classes, programs can be compiled. To show C++ program
as a truly Object Oriented program- it must be a collection of classe (s) and objects.
Various IDE’s (Integrated Development Environment) are available for compiling C++
code. TurboC++ is one of the basic C++ IDEs with Turbo C++ compiler (Borland’s
compiler). TurboC++ is not able to execute exception handling code using try catch
throw but other IDEs can do so.
Also namespaces were introduced in C++ after turboC.
Syntax of program differs little bit if using namespace std in program.
Like:
Code in dev C++, code block etc is like:
#include< iostream > //No need to mention .h with header file
#include< cstdio> 
using namespace std; //As namespaces were introduced in C++ after turbo
int main()

int a;
cin>>a;
cout<< a;
return 0;
}

On other side, same code in turboC++ will be like:


#include< iostream.h> //.h is used with header file

#include< conio.h> 
void main()

clrscr ();
int a;
cin>>a;
cout<< a;
getch ();
}

1.3 STANDARD LIBRARIES

Standard C++ programming is divided into three important parts:


● The core library includes the data types, variables and literals, etc.
● The standard library includes the set of functions manipulating strings, files,
etc.
● The Standard Template Library (STL) includes the set of methods manipulating
a data structure.

1.4 C++ BASIC INPUT / OUTPUT

C++ I/O operation uses the stream concept. Stream is the sequence of bytes or flow of
data. It makes the performance fast.
If bytes flow from main memory to device like printer, display screen, or a network
connection, etc, this is called as output operation.
If bytes flow from a device like printer, display screen, or a network connection, etc to
main memory, this is called an input operation.

1.5 C++ Variable

A variable is a name of memory location. It is used to store data. Its value can be
changed and it can be reused many times. It is a way to represent memory location
through symbol so that it can be easily identified.
Let's see the syntax to declare a variable:
type variable_list;   
The example of declaring a variable is given below:
1. int x;    
2. float y;    
3. char z;    
Here, x, y, z are variables and int, float, char are data types.
We can also provide values while declaring the variables as given below:
1. int x=20, b=40;  //declaring and initializing 2 variable of integer type    
2. float f=10.8;    
3. char c='G';    

Rules for defining variables


A variable can have alphabets, digits and underscore.
A variable name can start with an alphabet and underscore only. It can't start with a
digit.
No white space is allowed within the variable name.
A variable name must not be any reserved word or keyword e.g. char, float etc.
Valid variable names:
1. int a;    
2. int _ab;    
3. int a30;    
Invalid variable names:
1. int 30;    
2. int x y;    
3. int double;  

1.6 C++ DATA TYPES

Following are data types in C++ language.

Types Data Types

Built-in (Basic) Data Types : int, char, float, double, void


Derived Data Types : array, function, pointer, etc
User Defined Data Types : structure, union, class, enum

A data type specifies the type of data that a variable can store such as integer,
floating, character etc. Following figure depicts C++ data types.
Figure: C++ Data types

Explanation of various data types:


Built-in Data Types
These are also called fundamental data types which are a total of five.
These are integer-based and floating-point based. C++ language supports both signed
and unsigned literals.
The memory size of basic data types may change according to the 32 or 64 bit
operating system.
Following is a list of sizes of various data types according to the 32 bit OS.

Data Types Memory Size Range


char 1 byte -128 to 127
signed char 1 byte -128 to 127
unsigned char 1 byte 0 to 127
short 2 byte -32,768 to 32,767
signed short 2 byte -32,768 to 32,767
unsigned short 2 byte 0 to 32,767
int 2 byte -32,768 to 32,767
signed int 2 byte -32,768 to 32,767
unsigned int 2 byte 0 to 32,767
short int 2 byte -32,768 to 32,767
signed short int 2 byte -32,768 to 32,767
unsigned short int 2 byte 0 to 32,767
long int 4 byte
signed long int 4 byte
unsigned long int 4 byte
float 4 byte
double 8 byte
long double 10 byte

Derived Data Types


Derived data types are programmer declared data types. These are also called
extended data types. These are used to extend the behaviour of an existing simple
data type to get more functionality. It is used to handle more than one value at a time
using a single identifier. 
A derived data type is a collection of data types that describes the rules for
interpreting the information stored in a contiguous region of memory. Both the C and
the C++ languages provide syntax for declaring derived data types. 

Details about Derived Data Types:


1. Array: An array is a set of elements of the same data type that are referred to by
the same name. All the elements in an array are stored at contiguous (one after
another) memory locations and each element is accessed by a unique index or
subscript value. The subscript value indicates the position of an element in an array.
E.g. int a [20].
2. Function: A function is a self-contained program segment that carries out a
specific well-defined task. In C++, every program contains one or more functions
which can be invoked from other parts of a program, if required. E.g. int sum (int, int).
3. Pointer: A pointer is a variable that can store the memory address of another
variable. Pointers allow using the memory dynamically. That is, with the help of
pointers, memory can be allocated or de-allocated to the variables at run-time, thus,
making a program more efficient.
4. Reference: A reference is an alternative name for a variable. That is, a reference is
an alias for a variable in a program. A variable and its reference (location) can be used
interchangeably in a program as both refer to the same memory location. Hence,
changes made to any of them (say, a variable) are reflected in the other (on a
reference).

User Defined Data Types


User defined data types are created by a user by using simple, derived, user defined
data types as per the user requirement. The user has to decide the functionality and
behavior of these data types.
Various user-defined data types provided by C++ are structures, unions,
enumerations and classes.

1. Structure: Structure definitions have several formats, all of which include data
members and member functions. To show the formats for structure definitions, let's
look at structure data members first. The first structure format appears frequently in
header files.

struct_name
{
type data_member1;
type data_member2;
type data_membern;
};
The word struct_name is a new data type. Data members may be any type, including
pointers, references, arrays, and other structures whose types do not have the same
name as struct_name. The compiler does not allocate memory with this format
because we define only a type and not a variable.

2. Union: Unions are like structures, but data members overlay (share) memory, and
unions may access members as different types. We use structures and unions in
applications that need user-defined types, such as databases, windows and graphics.

It means, unions have the same formats as structures. Unlike structures, which
reserve separate chunks of memory for each data member, unions allocate only
enough memory to hold the largest data member.

3. Class: Structure and union are the significant features of C language. Structure


and union provide a way to group similar or dissimilar data types referred to by a
single name. However, C++ has extended the concept of structure and union by
incorporating some new features in these data types to support object -oriented
programming.

C++ offers a new user-defined data type known as class, which forms the basis of
object-oriented programming. Class acts as a template which defines the data and
functions that are included in an object of a class. Classes are declared using the
keyword “class”. Once a class has been declared, its object can be easily created.

4. Enumeration: An enumeration is a set of named integer constants that specify all


the permissible values that can be assigned to enum variables. These set of
permissible values are known as enumerators. For example, consider this statement.

enum country {US, UN, India, China};       // enum type declared


In this statement, an enumeration data-type country (country is a tag name),
consisting of enumerators US, UN, India and China. These enumerators represent
integer values, so any arithmetic operation can be performed on them. By default, the
first enumerator in the enumeration data type is assigned the value zero. The value of
subsequent enumerators is one greater than the value of the previous enumerator.

So, the value of US is 0, UN is 1, India is 2 and China is 3. However, these default


integer values can be overridden by assigning values explicitly to the enumerator was
shown here.

           enum country {US, UN=3, India, China} ;

In this declaration, the value of the US is O by default, the value of the UN is 3, India
is 4 and China is 5.

Once an enum type is declared, its variables can be declared using this statement.

           country countryl, country2;

These variables countryl, country2 can be assigned any of the values specified in
enum declaration only. For example, consider these statements.

            countryl India; // valid

            country2 Japan; // invalid

C++ also allows creating special type of enums known as anonymous enums, that is,
enums without using tag name as shown in this statement.

            enum {US, UN=3, India, China};

The enumerators of an anonymous enum can be used directly in the program as


shown here.

int count = US;

5. The typedef Keyword
C++ provides a typedef feature that allows defining new data type names for existing
data types that may be built-in, derived or user-defined data types. For example,
consider this declaration.

                                               typedef int integer;

In this declaration, a new name “integer” is given to the data type int. This new name
now can be used to declare integer variables as shown here.

                                                 integer i, j, k;
1.7 C++ KEYWORDS

A keyword is a reserved word. It cannot be used as a variable name, constant name


etc.
A list of 32 Keywords in C++ Language which are also available in C language are
given below.

auto break case char const continue default do


double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while

A list of 30 Keywords in C++ Language which are not available in C language are given
below:

asm dynamic_cast namespace reinterpret_cast bool


explicit new static_cast false catch
operator template friend private class
this inline public throw const_cast
delete mutable protected true try
typeid typename using virtual wchar_t

1.8 C++ OPERATORS


An operator is simply a symbol that is used to perform operations. There can be many
types of operations like arithmetic, logical, bitwise etc.
There are following types of operators used to perform different types of operations in
C++ language.

● Arithmetic Operators
● Relational Operators
● Logical Operators
● Bitwise Operators
● Assignment Operators
● Unary operators
● Ternary or Conditional Operator
● Special (Misc) Operators
Operators according to unary/binary/ternary collection:

Type Sub Type Operator Symbol


Unary Unary Operators ++
Operators (increment / decrement) --
Arithmetic Operators +, -, *, /, %
(add, subtract, multiple, divide, modulus)
Binary Relational Operators <,<=,>,>=,~,^
Operators (less than, greater than etc.)
Logical Operators &&, ||, !
(logical AND, logical Or etc.)
Bitwise Operators &, |, <<, >>, ~, ^
(bitwise AND, bitwise OR etc.)
Assignment Operators =, +=, -=, /=,%=
(equal t0 , add and then equal to etc.)
Ternary/ Ternary/Conditional Operator ?:
Conditional
Operator
Precedence of Operators in C++
The precedence of the operator's species determines which operator will be evaluated
first and next. The associativity specifies the operator's direction to be evaluated, it
may be left to right or right to left.
Let's understand the precedence by the example given below:
1. int data = 5 + 10 * 10;    
2. The "data" variable will contain 105 because * (multiplicative operator) is evaluated
before + (additive operator).
3. The precedence and associativity of C++ operators is given below:

Category Operator Associativity


Postfix ( ) [ ] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Right to left
Shift <<>> Left to right
Relational <<= >>= Left to right
Equality == !=/td> Right to left
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Right to left
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right

1.9 ORGANIZATION OF A C++ PROGRAM


Program in C++ can be written without using class and with classe also. A pure C++
program typically consists of a number of objects, which communicate with each other
by calling one another’s member functions. Before starting C++ language as an OOP
language, you must learn about how to write, compile and run a simple C++ program.
To write a simple C++ program, open the C++ console and write the following code.
// This code is in Turbo C++ IDE as namespace std is not used
#include <iostream.h>  
#include<conio.h>  
void main() 
{  
  clrscr();  
   cout << "Welcome to C++ World of Programming.";   
   getch();  

}  

In this book, in further chapters either Turbo C++ compiler for Code Block C++
compiler is used.
As written in above example:
#include<iostream.h> includes the standard input output library functions. It provides
cin and cout methods for reading from input and writing to output respectively.
#include includes the console input output library functions.
The getch() function is defined in the conio.h file.
The main() function is the entry point of every program in C++ language. The void
keyword in void main () specifies that it returns no value.
cout<< "Welcome to C++ Programming." is used to print the data "Welcome to C++
Programming." on the console.
getch() The getch() function asks for a single character. Until you press any key, it
blocks the screen.
1.10 FEATURES OF OBJECT-ORIENTED LANGUAGE

Following diagram illustrates various C++ features.

Simple
Portable
Compiler based

Object-Oriented
Mid-Level

Extensible C++ Features Structured

Recursion Rich-Library

Pointers Memory Management

Faster

Figure: Features of C++

List of various features of C++:


1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. Structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
11. Object Oriented
12. Compiler based
Detail about features:
1. Simple
C++ is a simple language as it provides a structured approach (to break the problem
into parts), a rich set of library functions, data types etc.
2. Machine Independent
It means portable. Unlike assembly language, c programs can be executed on many
machines with little bit or no change. But it is not platform-independent.
3. Mid-level programming language
C++ is also used to do low level programming. It is used to develop system applications
such as kernel, driver etc. It also supports the feature of high level language. So, it is
known as a mid-level language.
4. Structured programming language
C++ is a structured programming language as it is possible to break the program into
parts using functions. So, it is easy to understand and modify.
5. Rich Library
C++ provides a lot of inbuilt functions that makes the development fast.
6. Memory Management
It supports the feature of dynamic memory allocation. In C++ language, we can free
the allocated memory at any time by calling the free () function.
7. Speed
The compilation and execution time of C++ language is fast.
8. Pointers
C++ provides the feature of pointers. We can directly interact with the memory by
using the pointers. We can use pointers for memory, structures, functions, arrays etc.
9. Recursion
In C++, it is possible to call the function within the function. It provides code
reusability for every function.
10. Extensible
C++ language is extensible because it can easily adapt new features.
11. Object Oriented
C++ is an object oriented programming language. OOPs makes development and
maintenance easier whereas in Procedure-oriented programming language it is not
easy to manage if code grows as project size grows.
12. Compiler based
C++ is a compiler based programming language, it means without compilation no C++
program can be executed. First we need to compile our program using a compiler and
then we can execute our program.
1.11 CHARACTERISTICS OF OBJECT-ORIENTED LANGUAGE
C++ is an object-oriented language with several characteristics which favour making it
a pure object based language. Following is a list of various characteristics of object-
oriented language.
1. Classes
2. Objects
3. Data Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
7. Data hiding
8. Dynamic binding
Message passing

Details about Characteristics:

1. Classes
A class is a logical entity. It is a template or blueprint that defines the
characteristics of an object and describes how the object should look and
behave.

2. Objects
Object is an instance of a class. It is also called a real world entity. It
combines both data and member functions. Objects are the basic run-time
entities in an object-oriented system.

3. Data Abstraction
“Eliminate the Irrelevant, Amplify the Essential”
Abstraction is to focus on the essential and discard the irrelevant. In a way
this does not make sense unless you have a scope. Basically it separates
concept (interface) from implementation.
So, it is true that abstraction is the concept of exposing only the required
essential characteristics and behaviour with respect to a context. It is an
outer layout of process and is ‘design’ like in case of mobile- outer look is-
display screen & keypad to dial a number.
Other examples –
Abstraction shows only important things to the user and hides the internal
details, for example, when we ride a bike, we only know about how to ride
bikes but cannot know about how it works? And also we do not know the
internal functionality of a bike.

Abstraction is ATM Machine; All are performing operations on the ATM


machine like cash withdrawal, money transfer, retrieve mini-statement…etc.
but we can't know internal details about ATM.

4. Encapsulation
"Hiding the Unnecessary"
Encapsulation = Data Hiding + Abstraction.
Encapsulation is hiding the unnecessary.
Data encapsulation is a process. It focuses on the data inside the capsule.
It means hide those things which we want to hide from other people. It
represents the inner layout, in terms of implementation like in the case of
mobile phones, how the keypad buttons and display screen are connected for
performing operations like dial a number.
Other examples:
A teacher does not need to know how a student does her assignment (let
OOPs assignment). She is more interested in the end product.
Let us take an example of a power steering mechanism of a car. Power
steering of a car is a complex system, which internally has lots of
components tightly coupled together, they work synchronously to turn the
car in the desired direction. It even controls the power delivered by the engine
to the steering wheel. But to the external world there is only one interface
available and the rest of the complexity is hidden. Moreover, the steering unit
in itself is complete and independent. It does not affect the functioning of any
other mechanism. Data encapsulation is one of the mechanisms of data
hiding. It an be rectified that encapsulation protect the system, since it hides
stuff that can be vulnerable to malicious attack.

5. Inheritance
"Modeling the Similarity"
Inheritance is a way to reuse once written code again and again. The class
which is inherited is called base class & the class which inherits is called
derived class. Base class in inheritance mechanism is also called parent class
and derived class is also named as child class. So when a derived class
inherits a base class, the derived class can use the functions which are
defined in base class, hence making code reusable.
As similarities often exist in the world.
As shown in image below, one could easily see that there are some
similarities between the two Presidents of the United States, George H.W
Bush (41st President) and George W. Bush (43rd President).

Similarity in look, but not same as father – son relation


George W. Bush is a son of George H.W Bush. He inherits biological features
from his father, at the same time, has his own unique feature that one could
identify him as George W. Bush. This brings us to the idea of inheritance that
models a “is a” relationship between objects.
Example :
Father gives his property to child,
Father got those properties from child’s grandfather,
So child is the taker and father is giver,
Hence father works as a base class and child as derived class.
Vice versa is not possible. It means, the child couldn’t give its property to the
father so inheritance is one sided.

6. Polymorphism
"Same Function, different behavior"
The word “Polymorphism” comes from two Greek words, “many” and “form”.
We can illustrate the idea of polymorphism easily using the scenario where
different animals are asked to “speak”.
It is an object-oriented programming term. The ability to have methods with
the same name, but different content, for related classes. The procedure to
use is determined at run time by the class of the object. For example, related
objects might both have Draw methods. A procedure, passing such an object
as a parameter, can call the Draw method without needing to know what
type of object the parameter is.
The process of representing one thing in multiple forms is known as
Polymorphism.
Example - Suppose if you are in the classroom, at that time you behave like a
student, when you are in market at that time you behave like a customer,
when you at your home at that time you behave like a son or daughter. Here
one person presents in different-different behaviours.
The common example in daily life for polymorphism can be your behavior
which differs at school, work and home. What is common here is behavior, so
it is an interface.
When input is school, behave has one output as you (object) behave in a
certain way at school.
When input is work, behave has another output as you behave differently at
work. When input is home, behavior has yet another output. Three cases
have three different outputs because the input is different, but the interface
(behave) is the same and more importantly there is only one object (you).
Technically polymorphism is one interface different behavior due to different
objects of similar/related type.
Another example of polymorphism in real life, in an exam paper, each
student writes a different answer to the same question (assuming the
question requires a descriptive answer). Here there is only one interface
which is a question in the exam paper. It has different behavior (answers)
due to different objects (students) of similar/related type (human).

7. Data hiding
Data hiding is both a process and a technique. Data in data hiding is private
and non-accessible.
It provides not only less data complexity, but also data protection and
security. It concerns restrictions on terms of access and use. It is used in
classes by making data private.

8. Dynamic binding
It is related to rum-time calls.
Dynamic refers to the linking of a procedure call to the code to be executed in
response to the call. Dynamic binding means that the code associated with a
given procedure call is not known until the time of the call at run-time. It is
associated with polymorphism and inheritance. A function call associated
with a polymorphic reference depends on the dynamic type of that reference.

9. Message passing
In object oriented programs, basically objects communicate with each other.
This processes of communication involves the following basic steps:
     1.Creating classes that define objects and their behavior.
     2. Creating objects from class definitions.
     3. Establishing communication among objects.
1.12 COMPARISON BETWEEN PROCEDURAL PROGRAMMING PARADIGM AND
OBJECT-ORIENTED PROGRAMMING PARADIGM

S.No. Procedural programming paradigm Object-Oriented programming


(Procedure Oriented Programming) paradigm
(Object Oriented Programming)
1 In POP (Procedure Oriented In OOP (Object Oriented
Programming), a program is divided Programming), a program is divided
into small parts called functions. into parts called objects.
2 POP follows the Top Down OOP follows the Bottom Up approach.
approach.
3 POP does not have any access OOP has access specifiers named
specifier. Public, Private, Protected, etc.
4 In POP, Importance is not given to In OOP, Importance is given to the
data but to functions as well as data rather than procedures or
sequence of actions to be done. functions because it works as a real
world.
5 To add new data and functions in OOP provides an easy way to add new
POP is not so easy. data and function.
6 In POP, Data can move freely from In OOP, objects can move and
function to function in the system. communicate with each other through
member functions.
7 Function uses Global data for data cannot move easily from function
sharing that can be accessed freely to function, it can be kept public or
from function to function in the private so we can control the access of
system. data
8 Does not have any proper way for OOP provides Data Hiding so provides
hiding data so it is less secure. more security.
9 Overloading is not possible. Overloading is possible in the form of
Function Overloading and Operator
Overloading.
10 C follows the procedural Oriented C++ is multi-paradigm. It supports
programming style. both procedural and object oriented
programming styles.
11 Data is less secure in it. Data is secure as classes are used
which have modifiers.
12 Exception handling is not easy in C. C++ provides exception handling
It has to be performed using other using Try and Catch blocks.
functions.
13 C language comes under it- C++ language comes under it- it
Which does not support function supports function overloading,
overloading, functions in structure functions in structure can also be
cannot be used. used.
14 Operator overloading is not possible Operator overloading is possible in it.
in it.
15 Examples of POP are: C, VB, Examples of OOP are: C++, JAVA,
FORTRAN, Pascal. VB.NET, C#.NET.
1.13 BASIC CONCEPTS OF OBJECT-ORIENTED PROGRAMMING
The Concept of a Class
Class is a group of objects sharing common characteristics and behavior.
It is a blueprint for the object.
It is a collection of objects (or values) and a corresponding set of methods.
A class encapsulates the data representation and makes data access possible at a
higher level of abstraction.
Our real life has a lot of examples like:
● ‘Animal’ is a class and ‘Cow, Goat, Lion, Sheep’ etc. are objects.
● ‘Pencil’ is a class and ‘Camlin’, ‘Apsara’ etc. are objects
● ‘Cold Drink’ is a class and ‘Pepsi’, ‘Limca’, ‘CocaCola’ etc. are objects
● One more example: A class can be accepted as a sketch (prototype) of a house.
It contains all the details about the floors, doors, windows etc. Based on these
descriptions we build the house. House is the object.
As many houses can be made from the same description, we can create many objects
from a class.

Declaring a Class
In C++ classes are declared by a keyword class which is written before its name. We
could make as many objects as we want and each object has its own space of fields
and functions in a memory.
Data Members: The variables declared in a class.
Member Functions: The functions declared in a class.

Concepts of an object
The object of a class is also known as its instance and the process of creating an
object is called instantiation of a class. For example car, truck and crane are the three
objects of a class Vehicle; values could be assigned to objects after their declaration.
When class is defined, only the specification for the object is defined; no memory or
storage is allocated.
To use the data and access functions defined in the class, we need to create objects.
An object has: identity (a unique reference), social security number (SSN), employee
number, passport number state, etc called characteristics (variables) and behavior
(methods).
Characteristics such as hungry, sad, running, alive and behavior such as eat, wave,
smile
Interface and implementation of a class
An interface describes the behavior or capabilities of a C++ class without committing
to a particular implementation of that class. Abstract classes are used for creating
interfaces in C++. In other words, an interface is similar to an abstract class with the
following exemptions:
All methods defined in an interface are abstract. Interfaces can contain no
implementation.
Interfaces cannot contain instance variables. However, they can contain public static
final variables (ie. constant class variables)
Interfaces are declared using the "interface" keyword
If an interface is public, it must be contained in a file which has the same name.
Interfaces are implemented by classes using the "implements" keyword.
Implementing Interfaces: A Class can only inherit from one superclass. However, a
class may implement several Interfaces. The interfaces that a class implements are
separated by commas. Any class which implements an interface must provide an
implementation for all methods defined within the interface.
If an abstract class implements an interface, it NEEDS NOT implement all methods
defined in the interface. HOWEVER, each concrete subclass MUST implement the
methods defined in the interface.
Interfaces can inherit method signatures from other interfaces. These abstract classes
should not be confused with data abstraction which is a concept of keeping
implementation details separate from associated data.

Operations on objects

An object is an element (or instance) of a class; objects have the behaviors of their
class. The object is the actual component of programs, while the class specifies how
instances are created and how they behave.
Object-Oriented Terminology says sending a message to an object means asking the
object to execute or invoke one of its methods. Objects of a class are used for
accessing Data Members of Class. In the class-based object-oriented programming
paradigm, "object" refers to a particular instance of a class where the object can be a
combination of variables, functions, and data structures. Accessing a data member
depends solely on the access control of that data member. If it's public, then the data
member can be easily accessed using the direct member access (.) operator with the
object of that class.
If the data member is defined as private or protected, then we cannot access the data
variables directly. Then we will have to create special public member functions to
access, use or initialize the private and protected data members.

1.14 RELATIONSHIP AMONG OBJECTS

Association describes different types of relationships among objects of a class.


The figure shown below expresses types of relationships among objects.

Figure: Relationship among objects

It shows that the relationships among different objects can be expressed in several
ways which are described below:

1. Association
2. Aggregation
3. Composition
4. Dependency
5. Abstraction
6. Realization
7. Generalization
Details about different relationships
1. Association
It represents the relationship between two objects. It is also called a "has-a"
relationship that says one class is in some way associated with another class.

Association is a simple structural connection or channel between classes and is a


relationship where all objects have their own lifecycle and there is no owner. It means
both classes having association between them can be created and destroyed
independently.

If the association is between two classes then it is called binary association.


It is represented by a solid line.
It is multiplicity between objects like:
● One-to-one (1-1)
● One-to-Many (1-n)
● Many-to-one (n-1)
● Many-to-Many (n-n)
Example:
“An Employee works for a Company”
Employee Company

Take another example of Department and Student.


In one department, at the same time multiple students can be associated. Also single
students can associate with multiple departments. But there is no ownership between
the objects and both have their own lifecycle. Both can be created and deleted
independently.

0 ... * 0... *
Student Department

Course

Course class associates Student and Department class

2. Aggregation
Aggregation is a specialized form of Association where all objects have their own
lifecycle but there is an ownership like parent and child. Child object can not belong to
another parent object at the same time.
It contains a "has-a" relationship. Also pointer variables are used in it that point to an
object that lives outside the scope of the aggregate class. It is not responsible for
creating/destroying subclasses.
Take an example of Employee and Company:
A single Employee can not belong to multiple Companies, but if we delete the
Company then it doesn’t mean that Employee objects are also destroyed.
Model and Code for the above example is shown below:

Employee Company

Employee class has Aggregation Relationship with Company class

3. Composition
Composition is again a specialized form of Aggregation.
It is a strong type of Aggregation.
Here the Parent and Child objects have coincident lifetimes.
Child object does not have its own lifecycle. So, if a parent object gets deleted then all
of its child objects will also be deleted.
It is responsible for creation/destruction of subclasses
Take an example of a relationship between House and its Rooms:
House can contain multiple rooms, there is no independent life for room and any one
room can not belong to two different houses. If we delete the house then the room will
also be automatically deleted.
Model for the above example is shown below:

Room House

Room class has Composition Relationship with House class

4. Dependency
It is also called a using relationship, which means, one class is dependent on another
class. Dependency is defined as a relation between two classes, where one class
depends on another class but another class may or not may depend on the first class.
So, any change in one class can affect the functionality of the other class that depends
on it. For example, we have a Customer class and an Order class.
When we need to save a new order, we need to save it corresponding to a customer.
In order to do so, our Order class will need a reference to the Customer class and save
its data. So in this case, our Order class is dependent on the Customer class.
In the future, if any change is made to the Customer class, it may result in changes to
the Order class. Dependency representation is as below:
Dependency Class ---------------------------- > Dependent Class

5. Abstraction
Abstraction is specifying the framework and hiding the implementation level
information. Concreteness will be built on top of the abstraction. It gives us a
blueprint to follow while implementing the details.
Abstraction reduces the complexity by hiding low level details.
Example: A wire frame model of a car.
6. Realization
Realization relationships means, one class provides a specification and the other class
implements the specification.
Realization is a relationship between the blueprint class and the object containing its
respective implementation level details. This object is said to realize the blueprint
class. In other words, we can understand this as a relationship between the interface
and the implementing class. E.g. a particular model of a car that implements the
blueprint of a car realizes the abstraction.
7. Generalization
This implies an "is a" relationship.
It is also called an "is-a-kind-of" relationship.
One class is derived from another, the base class.
Generalization is implemented as inheritance in C++.
The derived class has more specialization.
It may either override the methods of the base, or add new methods. Examples are a
poodle class derived from a dog class, or a paperback class derived from a book class.

Useful symbols to represent relationship among objects:


Following figure makes clear various symbols which show the relationship between
objects.
Association
Inheritance
Realization/Implementa
tion
Dependency
Aggregation
Composition

Figure: Symbols representing relationships between objects in C++


1.15 ADVANTAGES OF OBJECT-ORIENTED PROGRAMMING INCLUDE

1. Improved software-development productivity


Object-oriented programming is modular, as it provides separation of duties in object-based
program development. It is also extensible, as objects can be extended to include new
attributes and behaviors. Objects can also be reused within and across applications.
Because of these three factors– modularity, extensibility, and reusability–object-oriented
programming provides improved software-development productivity over traditional
procedure-based programming techniques.
2. Improved software maintainability
For the reasons mentioned above, object-oriented software is also easier to maintain.
Since the design is modular, part of the system can be updated in case of issues without a
need to make large-scale changes.
3. Faster development
Reuse enables faster development.
Object-oriented programming languages come with rich libraries of objects, and code
developed during projects is also reusable in future projects.
4. Lower cost of development
The reuse of software also lowers the cost of development. Typically, more effort is put into
other object-oriented analysis and design, which lowers the overall cost of
development.
5. Higher-quality software
Faster development of software and lower cost of development allows more time and
resources to be used in the verification of the software. Although quality is dependent
upon the experience of the teams, object-oriented programming tends to result in
higher- quality software.

◆◆◆
Chapter 2
Classes and Objects
3.1 INTRODUCTION
▪ Classes are the most important and attractive feature of C++ that leads to Object
Oriented Programming.
▪ A Class is just a blueprint, which declares and defines characteristics and
behavior, namely data members and member functions respectively.
▪ Objects are specific instances of classes and so objects of a class will share its
characteristics and behavior.
▪ Objects are real world entities without which a class has no life. It means, a class
does not exist in reality if no object is created for it.
For example: 
A class of birds:
▪ All birds can fly and they all have wings and beaks.
▪ Here flying is a behavior.
▪ Wings and beaks are part of their characteristics.
▪ Also there are many different birds in this class with different names but all have
such behavior and characteristics.

3.2 CLASS SPECIFICATION


▪ A class is a combination of variables and functions. The variables inside class
definition are called as data members and the functions are called member
functions as depicted in the following figure.
Class name
Data Members of Class
Member Functions of
Class
Figure: Class representation in C++
▪ Basically a class is a user defined data type, which holds its own data members
and member functions.
▪ Following figure explains CSE named class with record of data members as:
▪ Total number of faculty works currently and total number of students studying in
particular CSE department.
▪ Total four member functions are created from which two will gather information for
faculty and students and two will show their information.
▪ This one block provides encapsulation which is again one of the strongest features
of C++.

CSE
Class name
number_of_fac
ulty Data Members
number-
of_students
getrecord_facul
Member Functions
ty ()
getrecord_stud
ent ()
showrecord_fa
culty ()
showrecord_st
udent ()

Figure: Class represented for department- CSE


▪ These data members and member functions can be accessed and used by creating
instance of that class. Instances are objects.
▪ Following figure is best suitable to represent objects of a class.

Apple Class Name


class
Color Attributes
Taste Members
Display Behavior
()

Granny
Objects
smith
Color:
green
Taste:
sour
Display
()
Apple
class
Color:
red
Taste:
sweet
Display
()

Figure: Two objects created for class “AppleClass”


▪ A class definition starts with the keyword class followed by the class name; and the
class body, enclosed by a pair of curly braces { }. A class definition must be
followed either by a semicolon or a list of declarations.
Syntax of a class
class class_name
{
data members;
member functions //also called methods;
}

//Defining a class in C++


class Box
{
private:
double length;
double breadth;
double height;
protected:
public:
void getrecord ( )
{}
}; //end of a class
As mentioned above:
▪ A class named “Box” is logically created with three data members of type “private”
and one member function of type “public”. It does not contain any protected data.
▪ Private, Protected, Public are called visibility labels (access specifiers). Colon (:) is
mandatory to write after these three keywords: private, public and protected.
▪ The members that are declared private can be accessed only from within the class.
▪ Public members can be accessed from outside the class also.
▪ Protected members can only be accessed by their own class and by its direct child
class.
▪ In C++, data can be hidden by making it private.

3.3 CREATING CLASS OBJECTS AND USE OBJECTS TO ACCESS CLASS


MEMBERS
▪ C++ is a multi-paradigm programming language. That means, it supports different
programming styles.
▪ One of the popular ways to solve a programming problem is by creating objects,
known as object-oriented style of programming.
▪ C++ supports object-oriented (OO) style of programming which allows dividing
complex problems into smaller sets by creating objects.
▪ Objects give life to a class.
▪ It is true that object means a class in “runtime”.
▪ The object is the actual component of a program, while the class specifies how
instances are created and how they behave.
▪ Object is simply a collection of data and functions that act on that data.
▪ Object for a class can be created by writing class name then space and then object
name.
▪ It is created in the main () function from where program execution starts.
Example below represents obj is object created for class named ABC
class ABC
{
int x;
void display( )
{ } //empty function
};
void main()
{
ABC obj; // Object of class is created
}

3.4 ACCESSING THE DATA MEMBERS OF A CLASS


If the members are private then cannot be directly accessed outside the class as
outsiders cannot use private data.
If the members of a class are public then can be easily accessed outside the class.
Same concept is mentioned in the below example. The public data members of objects
of a class can be accessed using the direct member access operator (.) also called dot
operator.
//Example showing access of public data members outside the class
#include <iostream>
using namespace std;
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
}; // end of class
int main( )
{
Box ob; // Declare object of class Box
double volume = 0.0; // Store the volume of a class Box here

// Box specification
ob.height = 4.0;
ob.length = 6.0;
ob.breadth = 3.0;

//volume of box
volume = ob.height * ob.length * ob.breadth;
cout <<"Volume of Box : " << volume <<endl;
return 0;
}
Output:
Volume of Box: 72

Above example illustrates:


Class Box has three public data members only declared, not initialized.
In main (), an object of Box class is created and with the help of this object, data
members height, length and breadth (which are public) are initialized values 4.0, 6.0
and 3.0. Basically, a dot operator is used to call members of a class. Left side of the
dot is the object name of the class and the right side is the member of the class which
should be either public or protected in class but not private.
Then volume is calculated.
3.5 ACCESS SPECIFIERS IN A CLASS
Access specifier in C++ class defines the access control rules. C++ has 3 new keywords
introduced, namely:
1. public 2. private 3. protected
These access specifiers are used to set boundaries for availability of members of class.
Access specifiers in the program are followed by a colon. We can use one, two or all 3
specifiers in the same class to set different boundaries for different class members.
Description of access specifiers:
1. Public: Data members or Member functions which are declared as public can be
accessed anywhere in the program (within the same class, or outside of the class).
2. Private: Data members of Member functions which are declared as private can be
accessed within the same class only i.e. the private Data members or Member
functions can be accessed within the public member functions of the same class.
3. Protected: Data members or Member functions which are declared as protected can
be accessed in the derived class or within the same class.
Same can be dictated by table below:

S Class Access Access Access


. member from from from
N access same derived object
o specifier class class outside
. classes
1 Public Yes Yes Yes
member
2 Private Yes No No
member
3 Protected Yes Yes No
member
Table: Access specifiers and accessibility of class members
Yes means members can be accessed. No means members cannot be accessed.
Syntax:
//Statements 1 to 3 depicts about access specifiers used in a class
//Statements 4 to 6 depicts about inheritance type
1) public : member-declarations
2) private : member-declarations
3) protected : member-declarations
4) class_name : public base_classes
5) class_name : private base_classes
6) class_name : protected base_classes
Explanation of above statements of syntax:
Statements 1 to 3:
1) The members declared after the public specifier has public member access.
2)  The members declared after the private specifier has private member access.
3)  The members declared after the protected specifier has protected member access.
Statements 4 to 6:
4)  Public inheritance: the members of the base classes listed after the specifier keep
their member access in the derived class. Eg. class Son: public Father
5)  Private inheritance: the public and protected members of the base classes listed
after the specifier are private members of the derived class.
E.g. class Son: private Father
6)  Protected inheritance: the public of the base classes listed after the specifier are
protected members of the derived class. Eg. class Son: protected Father

3.6 STORAGE CLASSES


A storage class defines the visibility and life-time of variables within a C++ Program.
These specifiers precede the type that they modify. In C++ Programming, there exist
following types of storage classes as shown in figure:

C++ Storage Classes

S. Storage Ke Lifetim Visib Initi


No Class yw e ility al
Name or Valu
d e
1 Automatic au Functio Local Garb
to n Block age
2 External ext Whole Glob Zero
er program al
n
3 Static sta Whole Local Zero
tic program
4 Register reg Functio Local Garb
ist n Block age
er
5 Mutable m Class Local Garb
ut age
abl
e
Table: Storage classes
Details:
1) Auto:
It is the default storage class for all local variables.
It means if a variable is defined inside a function then it is called automatic. So,
inside the main () function of C++, all variables are also automatic.
{
int rollno;
auto int phoneno;
}
Above example defines two variables with the same storage class i.e. both are
automatic, as auto means by default storage assigned.
2) External:
It is a kind of global variable that is visible to the whole program.
It is declared between header files and the program i.e. main ().
#include<iostream>
int a; //external variable
extern int b; //external variable
void main ()
{
……
}
Above examples makes it clear that if the extern keyword is not mentioned for external
variables, even then it is true that any variable declared between header files and start
of the main program is external. It means global visibility.
3) Static:
A static variable is initialized only once in the beginning. Re-initialization for static
variables is not true.
By default, it takes an initial value of zero.
See following example executed in TURBO C++:
#include<iostream.h>
#include<conio.h>
void main ()
{
void f1 (); //f1 () function declared
f1(); //f1 () function called
f1 (); //f1 () function called again
f1 ();
getch ();
}
void f1() // definition (body) of f1 () function
{
static int c=2;
c++;
cout<<”\n value of C = “<<c;
}

Output:
value of C = 3
value of C = 4 output when used concept of static
value of C = 5

Now make a non static type of variable i.e. replace statement static int c=2 with int c=2.
Now output will be:
value of C = 3
value of C = 3 output when variable is not static
value of C = 3
If the f1 () function is called three times then- it is not initialized each time from its value 2 but
will have a previous update.

4) Register:
This storage class is used to store variables in CPU registers instead of RAM. So, the
maximum size of a variable can be equal to the register size.
Prefer this storage for variables that require quick access.
To store the contents of counter variables, registers can be used.
Syntax:
register int var;
If it is not initialized then it stores garbage value.
It has local scope.

5) Mutable:
This is a type of storage class which is not available in C language but is added in C++
as auto, register, static and extern are the storage class in C also. 
Sometimes there is a need to modify one or more data members of a class through
const function although it is true that const function can’t update any other value.
This task can be easily performed by using mutable keywords.
Syntax:
mutable int var;
Mutable is mainly useful if in case most of the members should be constant but a few
need updates.
Data members declared as mutable can be modified even though they are the part of
the object declared as const.
//Consider the following example executed in code Blocks IDE: #include
<iostream>
using namespace std;
class M
{
public:
int a;
mutable int b;
M()
{
a = 10;
b = 20;
}
};
int main()
{
const M o1; // o1 is object of class named M but of const type
o1.b= 30;
cout << o1.b;
return 0;
}
Output
30
As o1 is an object of constant type still it can modify values of mutable data members.
So the output of the above program is not 20 for the b variable, it is 30.

3.7 STATIC AND CONSTANT MEMBERS IN A CLASS

In a class, it is possible to make its both data members and member functions of type
static. Following part covers firstly static data members and then static member
functions.
Static Data Members
If a data let int count of a student is created as static then keyword static will precede
it as:
“static int count”
Now for the count variable, only one copy will be created which is accessible for the
whole class.
It is mandatory to define the following statement outside the class for all static data
members.
▪ Use scope resolution to represent type and scope of static data members: let name
I am a student.
o int student :: count ; //c is assigned value zero
or
o int student :: count =1629; //c is assigned value 1629
Static variables are not re-initialized each time as it is called but maintains value
common to the whole class.
//Following example represents use of static data members in a class:
#include<iostream>
using namespace std;
class student
{
static int count; //count variable is of type static and is in private scope

public:
void get ()
{
++count;
}
void show ()
{
cout<<"\n Counting is = "<<count;
}
};
int student :: count; //Mandatory declaration
int main ()
{
student ob1, ob2; //2 objects created for student class
ob1.show (); //count value 0
ob2.show (); //count value 0
ob1.get ();
ob2.get ();
ob1.show (); //count value 2
ob2.show (); //count value 2
return 0;
}
Output
Counting is = 0
Counting is = 0
Counting is = 2
Counting is = 2

Explanation of above program:


It means: a variable of type static maintains its previous value.
So, in the above example: static int count is having value 2 as get () is called twice. In
the first call: get () assigned ++count i.e. ++0 which is 1. Again when get () is called a
second time- now ++1 is performed because it is not re-initialized in each call again
from its initialized value.
Static Member Functions in a class
Same like data members can be static, it is possible to make member functions of a
class as static.
Its properties are:
▪ It can only access those members of its own class which are also static.
▪ Let student is a class and output count () is a function of class which is going to be
static member function of class then must go:
static void output count ()
{
//only use static variables of class, not others
}
▪ Must use following statement to show type and scope of static members outside the
class for static data members as explained in above section
int classname :: static variable name;
▪ Must use the following statement to show type and scope of static members ;
//inside the main () when you want to call a static function.
classname :: static functionname
//Example represents use of static member function in a class.
#include<iostream>
using namespace std;
class student
{
static int count;
int total;
public:
void get ()
{
++count;
total = count;
}
void show ()
{
cout<<"\n Total strength "<<total;
}
static void outputcount ()
{
cout<<"\n Counting is = "<<count;
}
};
int student :: count;
int main ()
{
student ob1, ob2;
student :: outputcount(); //call static fuction so output : 0
ob1.get (); //count has become 1 and total=1
ob2.get (); // count has become 2 and total=2
student :: outputcount() ; //call static function so now output 2
ob1.show ();
ob2.show ();
return 0;
}
Output
Counting is = 0
Counting is = 2
Total strength 1
Total strength 2
Const Members by using const keyword
If a data member of a class is const then it becomes constant and cannot be changed.
We can use the initialized list in the constructor to initialize it.
Also, the constant variables must be initialized while declared.
Const itself is a keyword and is available in both C and C++.
Syntax:
const int c;
//C++ example using const keyword
Above code will print compiler error “increment of read-only variable 'i'' for statement i + +; It
means 1 (which is a constant data member) cannot be changed.
Same code will print the following output if the constant value will not be updated.
#include<iostream>
using namespace std;
int main ()
{
const int i = 10;
const int j = i+10; // Works fine
//i++; //i is not changed, so no error
cout<<"Value of i "<<i<<"\n"<<"Value of j "<<j;
return 0;
}
Output
Value of i 10
Value of j 20
Const Member functions
As const represents constant which means not to modify. So if a function is of type
constant using keyword const then such function cannot alter any data in a class. If it
does so, the compiler gives an error. We can say- const function can only use other
members of class as such but cannot modify it. It is important to note that keyword
const is not mentioned prior to function which is of type constant but after function
(not in case of constant data member) i.e.:
void show () const;
If a programmer wants to write a body of constant member function outside the class
and only wants to declare it inside class then: const keyword is used in both
statements.
It can use even those data values which are not constant (was not possible in case of
static member function).
//Example represents use of const member function in a class.
#include<iostream>
using namespace std;
class student
{
int rollno;
public:
void get ()
{ rollno = 16;

}
void show () const
{ rollno = 20; //error
cout<< "Roll no is"<<rollno; }
};
int main ()
{
student ob;
ob.get ();
ob.show ();
return 0;
}
Output: [no output] as Compilation failed due to following error(s).
Compiler error as show () is a const function so cannot change with others.
Error message: assignment of member 'student::rollno' in read-only object

Following code is correct code:


//Example represents use of const member function in a class.
#include<iostream>
using namespace std;
class student
{
int rollno;
public:
void get ()
{ rollno = 16;
}
void show () const
{ cout<< "Roll no is "<<rollno;
}
};
int main ()
{
student ob;
ob.get ();
ob.show ();
return 0;
}
Output
Roll no is 16

3.8 FRIENDS OF A CLASS


In C++, one class can have friends to whom a class allows to access its own secure
members.

Friend of a class

Friend function Friend class

Figure: Friends of a Class


Friend Class
A friend class in C++ can also access the private and protected members of a class in
which it is declared friend.
There are some important facts about friend class concept:
▪ Friendship is not mutual.
o It means if A is friend of B then:
It is not true for: B is also a friend of A.
o So, it is clear that if class B is declared as friend in class A using friend keyword
but class A is not declared as friend in B class then: permission is only to B for
accessing privacy of A class. On the other hand, A is not permitted to use the privacy
of B in its own class.
▪ Friendship cannot be inherited.
o If B is friend of A, C is friend of B and C is derived class of B then:
C has no authority to access A class.
▪ The concept of friends in programming is not so popular. So, make use of friends for a
limited purpose.
▪ Too many friends mean more outsiders accessing private and protected data, which
can result in lessening the value of encapsulation.
▪ This concept is not used in JAVA programming language (JAVA is pure Object-
Oriented language at extended level) as privacy visible outside the scope of a class is a
loophole, not a beneficial point.

//Syntax
class classname1
{
private:
……..
public:
……..
friend class classname2;
}; //closing class classname1
class classname2
{
private:
……..
public:
……
classname2 (classname1 object)
{//access classname1 private data using its object
}
};
main function
{
classname1 object1;
classname2 object2;
pass object1 as parameter to object2;
}
As mentioned in syntax written above, classname2 is friend of classname1.
Follow the example written below to clear the concept of friend class.
#include<iostream>
using namespace std;
class A
{
double accno;
public:
A() // constructor of class A
{
accno= 12345;
}
friend class B; //B is another class and is friend of a class
}; //closing class A
class B
{
public:
void show (A ob) //ob is object created for class A
{
cout<<"private details of class A: ";
cout<<ob.accno;
}
};
int main ()
{
A ob1;
B ob2;
ob2. show (ob1); //ob2 (object of class B) will print private details of class A
return 0;
}
Output
private details of class A: 12345
Explanation
First thing to remember is- Do not repeat the keyword friend when writing body of
friend class. It is sufficient to inform the compiler by writing it only inside the class for
which it is a friend.
It means:
friend class B // IT IS WRONG (Friend should not be written here )
{
public:
//body of friend class;
}
But:
friend class B;
Statement is true and compulsory as it is B class declaration and it should be inside A
class because B is Friend of A.
It is clear from above easily demonstrated example that:
▪ A and B are two classes
▪ B is a friend of A because it is declared as a friend inside the scope of A class.
▪ B class has only one public member function named show ().
▪ Show () function is having an argument which is an object of A class. It is mandatory
to pass object of A class in those functions of B which want to access private or
protected members of A class.
▪ Also in main () function, must pass object of A to B when it is going to call that
function which is using A’s private data (data in this case is accno).

Friend Function
A non-member function cannot access the private data of a class because private
access is only allowed to own member functions of a class.
But, in some situations, if an outsider function wants to access private data of a class
then: it is possible with the concept of Friend Function.
A friend function can be declared either in the private or public part of a class without
affecting its meaning.
So, a function can be declared as friend of a class inside the scope of class like:
class A
{
friend void use ( A ob);
}
// It shows that- “A” is a class and “use” is a function which is a friend of A class
called friend function.
Such functions should only be declared inside class. Its definition (body of function)
should be outside the class. Keyword friend precedes function when declared as friend
inside class scope.
Do not repeat keyword friend when defining body of function.
//Syntax
class A
{
……
…….
friend return-type function-name (argument);
};

Now write the body of friend function outside the scope of class.
Do not use scope resolution operator (: :) to define the body of the friend function
because it is friend, not the own function of class.
Define it as
Return-type function-name (argument)
{
Body of friend function with use of private data of A class
}
Return-type of friend function can be void, int, float etc
Arguments passed to function are objects of class A.
It assures class A that only those are my friends which have arguments as objects of
my own class.
//Example using concept of friend function
#include<iostream>
using namespace std;

class A
{
int a, b;
public:
A (int x, int y ) // constructor of class A
{ a=x, b=y; }

friend int add (A ob); //add is function which is friend of A class


}; //closing class A
int add (A ob)
{
return (ob.a+ob.b);
}
int main ()
{
A ob1 (5,10);
int sum = add (ob1);
cout<<"Sum of private data is "<<sum;
return 0;
}
Output
SUM of private data is 15

Note that private members can be accessed by a friend function using dot operator
like:
ob.a to access a private member named a using object of A passed as argument.
ob.b to access a private member named b in the same manner as a is accessed.
Also in the main () function, the friend function (add) is called by passing an object of
A class. Do not call it as ob.add () because it is not a member function of class A which
is having object ob.
It is possible to create one function as a common friend of two or more classes at the
same time in the same program. Same statement of friend function is declared in all
classes having the same friend function.
One important thing for this scenario is called forward declaration.
According to the forward declaration, to intimate the compiler about more classes that
have common functions as friends, just declare those classes in the beginning of the
program after writing header files for which body will be written later. Such classes are
those who have the same friend function.
Let two classes class A and class B have the same friend function named sum.
If A’s body will be written before and then B’s body then:
Must do forward declaration of B before defining class A as follows:
//Example showing two classes having same friend function:
#include <iostream>
using namespace std;
class B; //forward declaration
class A
{
int a, b;
public:
A()
{
a=10, b=20;
}
friend void sum (A oa, B ob); // oa is object of A class, ob is object of B class
};
class B
{
int c, d;
public:
B()
{
c=30, d=40;
}
friend void sum (A oa, B ob); // oa is object of A class, ob is object of B class
};
void sum (A oa, B ob)
{
int s= oa.a + oa.b + ob.c + ob.d;
cout<<"SUM of Values through friend function : "<<s;
}
int main ()
{
A o1;
B o2;
sum (o1, o2);
return 0;
}
Output
SUM of Values through friend function: 100

3.9 VARIOUS TYPES OF CLASSES IN C++


3.9.1 Empty Class
3.9.2 Nested Class
3.9.3 Local Class
3.9.4 Container Class
3.9.5 Abstract Class

Explanation of different types of classes:


3.9.1 Empty Class
The class without any data members or member functions is called an empty class.
These classes are not frequently used in C++ programming as such classes cannot
have bodies.
Yet these are useful in exception handling.
Syntax:
class class-name { };

Another way to expressing empty class:


class class-name
{
// vacant means empty
};
Let vacant is name of a class then following statement shows vacant is empty class:
class vacant { };
One important point about empty class is:
Size of an empty class in C++ is =1 byte.
It is not 0 byte and if virtual function is declared inside it then size of such class
becomes automatically minimum 4 bytes.
Size of operator helps to calculate size of any class.
As we know that space is always needed to store something and the minimum amount
of memory cannot be zero, but can be one.
// Example to show size of an empty class:
#include <iostream>
using namespace std;
class empt
{ };
int main ( )
{ cout<< "SIZE Of AN EMPTY CLASS "<< sizeof (empt);
return 0;
}
Output:
SIZE Of AN EMPTY CLASS 1
Use of virtual function in a class:

// Example to show size of an empty class when it has virtual function:


#include <iostream>
using namespace std;
class empt
{
public:
virtual void show ( )
{ }
};
int main ( )
{ cout<< "SIZE Of AN EMPTY CLASS "<< sizeof (empt);
return 0;
}
Output:
SIZE Of AN EMPTY CLASS 4
Execution of above example may show size 4 in some compilers and 8 in other
compilers.
It means if an empty class is just having an empty virtual function then the minimum
space occupied is not 1, it increases to 4.
3.9.2 Nested Class
A class is called a nested class if it is enclosed in another class. Here the term
enclosed means this class is defined inside another class.
So, a nested class is completely written inside the scope of the outer class.
Nested class can only be accessed within the scope of the class in which it is defined.
Let enclose and nest are two classes.
Class “nest” will be written completely (its body) inside another class which is named
“enclose” class as shown below:
class enclose
{
class nest
{ }; // end of nest class
}; //end of enclose class
Other names used for nested class and enclosed class.
Nested class also called inner class, inside class.
Enclosed class also called outer class, outside class and sometimes surrounding class.
Let A and B are two classes.
B is a nested class. So it will be written completely (its body) inside another class
which is A class as shown below:
Take another example:
class A
{
class B
{ }; //end of inner class (called nested class)
}; //end of outer class (called enclosing class)
Important facts about nested classes in C++:
Nested classes have access to private data of outer class
These classes are members of another class, so called inner classes. These class
members have the same access rights as other members of enclosing class have on it
even on private members.
This is not mutual i.e. vice-versa is not true. So, members of the enclosing class have
no special access to members of the private class.
These classes can be further of two types.
a. Static nested classes
b. Non-static nested classes
A Static nested class cannot access other members of enclosing (outer class). So,
nested classes should be of type non-static.
Why are nested classes used?
Concept of nested classes provides logical grouping of classes. So, classes useful at
one place can be nested.
▪ It is a useful tool in C++ which increases encapsulation.
▪ It provides more readable and maintainable code.
▪ It has a close conceptual relationship with the outer class.
▪ Always nest small classes into top-level classes for ease of high readability of code.
▪ It can be written in any access mode of outer class like in private, public or protected
with impact as shown in table below:
// Example illustrating concept of nested class
#include <iostream>
using namespace std;
class nestout
{
public:
class inner
{
private: int a, b, sum=0;
public:
void add (int x, int y)
{ a=x; b=y;
sum= a+b;
cout<<"SUM is "<<sum;
}
}; //inner class closed
}; // nestout class closed
int main ( )
{
nestout::inner ob1;
ob1.add (20, 30);
return 0;
}
Output
SUM is 50
As shown above, inner is a nested class and nestout is outer class. So, in main ( )
function, scope resolution is used to call member function of inner class with its object
through nestout class.
Nested classes can only use static and enum members of outer class.
3.9.3 Local Class
If a class is defined inside a function then it becomes a local class for that particular
function.
It means a class can be declared inside a function also.
That function can be even a member function of some other class.
Syntax
void function-name ( )
{
class class-name
{
public:
return-type function-name ( )
{
….
}
….
}; //local class closed here
class-name object-name;
object-name. function-name ( );
} //enclosing function closed here
main ()
{
call enclosing function;
}

// Example using local class concept in C++


#include <iostream>
using namespace std;
void func ( )
{
class loc
{
public:
void show ( )
{ cout<<"I am local"; }
}; //local class closed here
loc ob1; //object of local class created inside func ( )
ob1.show ( ); //local class functions also called inside scope of func ( )
} //enclosing function named func ( ) closed here
int main ( )
{
func ( ); // automatically show () of local class called here
return 0;
}
Output:
I am local
Some facts about Local Classes
The function which is enclosing a class inside it is also called a surrounding function
or enclosing function.
Static data members cannot be created for a local class.
It means following declarations are wrong inside local class
▪ Static int number;
▪ Static void get ( ) // Incorrect
{ }
Objects of local classes have local scope. It means you must create and use its objects
in the same enclosing function.
Following syntax is wrong:
void main ( )
{
local-class object; //wrong syntax…. only enclosing function can be called
}

Following syntax is correct.


void main ( )
{
enclosing function calling //correct syntax….
}
It means whatever is relevant to the local class, call or use all that inside the scope of
the enclosing function.
Scope resolution (: :) defines a class function outside the scope of class is not helpful
in case of local class.
According to this:
Following code is wrong:
void func ( )
{
class loc
{
public:
void show ( );
};
void loc : : show ( ) //wrong syntax
{ }
}
It means methods (member functions) of local class can not be defined outside the
scope of class.
Local classes can access:
▪ Other local classes of same function
▪ Global types
▪ Global variables and functions
It can be illustrated by following example:
#include <iostream>
using namespace std;
int x; // x is global variable
void func ( )
{
class loc1
{
public:
void show1 ( )
{
x=20;
cout<<"\ni am in local class 1 ";
cout<<" \nvalue given to global variable =" <<x;
}
}; //local class 1 closed here
class loc2
{
private:
loc1 ob1; //* local class 1 object created in local class 2
ob1.show1( ); // call function of local class 1 with its object in local class 2
public:
void show1 ( )
{
x=40;
cout<<"\n\nI am in local class 2 ";
cout<<"\nvalue given to global variable =" <<x;
}
}; //local class 2 closed here

loc2 ob2; //object of local class 2 created inside func ( )


ob2.show2( ); //local class 2 function also called inside scope of func ( )
} //enclosing function named func ( ) closed here
int main ( )
{
func ( ); // automatically show ( ) member function of local class called
here
return 0;
}
Output
i am in local class 2
value given to global variable = 20

i am in local class 2
value given to global variable = 40

It is possible that local classes’ member functions can access variables of enclosing
functions if the variables are static and enum.
Also it is possible that enclosing function can be a member function of a class as
shown below:
#include <iostream>
using namespace std;
class abc
{
public:
void func ( )
{
class loc //loc is local class as defined inside a function
{
public:
void show ( )
{
cout<<"I am local";
}
}; //local class closed here

loc ob1; //object of local class created inside func ( )


ob1.show ( ); //local class functions also called inside scope of func ( )
} //enclosing function named func ( ) closed here
}; // abc class closed here
int main ( )
{
abc obj;
obj.func ( ); // obj is object of abc class and func ( ) is member function of it
return 0;
}
Output:
I am local

3.9.4 Abstract Class


Base class in inheritance is named as abstract class i.e. it is designed to be specially
used as a base class.
Purpose: The purpose of an abstract class (referred as an ABC) is to provide a suitable
base class from which other classes can inherit.
Abstract classes cannot be used to instantiate objects.
It serves only as an interface means no need to create object of abstract class.
An abstract class contains at least one pure virtual function. A pure virtual function
can be created by using a pure specifier (= 0) in the declaration of a virtual member
function in the class declaration.

3.9.5 Container Class


Container class holds and organizes multiple objects (instances) of other classes.
It is an important category of ADT (Abstract Data Type).
It is used to maintain a collection of elements. So, following can be containers:
▪ Array
▪ Table
▪ Stack
▪ Queue
▪ Linked List
▪ Tree
It illustrates the concept of containership. As a container helps to organize and store
items that are placed inside it.
In the same manner, container classes hold and organize multiple objects (also called
instances) of other classes.
It is also used to maintain collection of elements
This concept of container is the basis for various C++ class libraries.
It means- do not create objects of different classes in main (), use the concept of
interface by making one class as a container and create other classes’ objects inside it.
Take an example of four classes in one program. Classes are: class doctor, class
patient, class ward and class contain.
As all these classes will have their own member functions, which normally we call in
main () function either by its own object or by the object of the last level derived class
if there exists an inheritance.
With the concept of container class- public members of a class can be called in a class
which acts as a container for other classes.
So, Instead of creating objects of all these in the main () function, select one class out
of these as containers in which other classes' objects can be created. All public
members of different classes will be called in the container class.
// Example illustrates concept of container class
#include <iostream>
using namespace std;
class doctor
{
char name [80];
public:
void get ()
{ cout<<"\n Enter Name of concerned doctor";
cin>>name; }
void show ()
{ cout<<"\n Name of concerned doctor is "<< name; }
};
class patient
{
char name1 [80];
public:
void get1 ()
{ cout<<"\n Enter Name of patient";
cin>>name1; }
void show1 ()
{ cout<<"\n Name of patient is "<<name1; }
};
class ward
{
char w[80];
public:
void get2 ()
{ cout<<"\n Enter ward number";
cin>>w; }

void show2 ()
{ cout<<" \n Ward no is "<<w; }
};
class contain
{
int dues;
doctor od;
patient op;
ward ow;
public:
void get3 ()
{
od.get ();
op.get1();
ow.get2();
cout<<"\n Enter dues if any";
cin>>dues;
}
void show3 ()
{
od.show ();
op.show1();
ow.show2();
cout<<"\n Pending dues are"<< dues;
}
};
int main ()
{
contain oc;
oc.get3();
oc.show3 ();
return 0;
}
Output:
Enter name of concerned doctor Aman
Enter name of patient XYZ
Enter ward number 2
Enter dues if any 3000

Name of concerned doctor is Aman
Name of patient is XYZ
Ward no is 2
Pending dues are 3000
3.10 BIT FIELDS AND CLASSES
Bit fields: These provide the exact amount of bits required for storage of values.
Actually this concept has a main focus on saving memory space.
It says- if record or information can be settled with the use of bits then avoid
allocating byte for it as byte based data will consume more memory space as
compared to bit based data.. For this, take an example of the status of traffic lights. It
informs either ON or OFF.
So, if a variable would be used for it, then its value will be 1 or 0. It means a total 2
bits are required for such type of storage. One bit for 0 value and another bit for 1
value.

Some facts about Bit fields


▪ It uses the colon operator instead of the return type of a variable. Colon operator
means the compiler will get that bit fields are used.
▪ It should always be of integer type. Not applicable on character and others.
▪ It is not useful for obtaining the address of a variable. It means not compatible with
& operator.
▪ It prefers macros declarations.

Example:
Use of bit field concept for storing information of a vehicle.

Information type Number of bits required Actual bit assigned


(bit field)
Vehicle is Petrol=1,
Petrol based or 2 diesel=2
Diesel based
Vehicle is: Two-wheeler=3,
Two (2) wheeler or 3 three-wheeler=4
Four (4) wheeler
Vehicle has 3 Old-model=5,
Old model or new-model=6
New model
Total Bits= 8 bits

It shows:
If a variable value is in range 0 to 3 then: bit field will be 2.
If a variable value is in range 0 to 7 and exceeding 3 then: bit field will be 3.
//Implementation of bit fields in classes:
#include <iostream>
using namespace std;
#define petrol 1
#define diesel 2
#define two_wheeler 3
#define four_wheeler 4
#define old_model 5
#define new_model 6 // all with #define are macros declarations
class vehicle
{
private:
unsigned fuel : 2;
unsigned type : 3;
unsigned model : 3; // bit field required
public:
vehicle ( )
{
model = old_model;
type = four_wheeler;
fuel = petrol;
}
void show ( )
{
cout<<"Your vehicle details are: \n";
cout<< model << endl << type << endl << fuel;
}
};
int main ( )
{
vehicle ob;
ob.show ( );
return 0;
}
Output
Your vehicle details are:
5
4
1
As shown in above example, macros are declared for various fields relevant to a
vehicle. Here, class name is vehicle which requires hardly one byte to store its
information about fuel (diesel or petrol), type of vehicle (two_wheeler or four) and about
its model (new or old).
Total 2 bits are needed to store information about fuel, total 3 bits for storing
information about type of vehicle and again 3 bits for storing information about model
of vehicle. Here, Colon operator is mandatory to assign bit fields.
The output:
The 5 mean model is old_model.
The 4 mean type is four_wheeler.
1 means it is petrol based.

◆◆◆◆◆

Chapter 3
Console Based Input/Output
C++ programming paradigm provides Input/output standard library with a wide set of
I/O streams that means streams of input flow and of output flow. Input/Output in C+
+ occurs in streams.

2.1 CONCEPTS OF STREAMS

▪ Streams are sequences of bytes flowing in and out of the programs.


▪ If stream is used in Input operations then:
❖ It means data is moving from an input device to the program.
❖ Input devices such as keyboard, file, network or another program.
▪ But if stream is used in Output operations then:
❖ It means data is moving from the program to an output device.
❖ Output device such as console, file, network or another program.

Input Source
Output Source
Input Stream
C++ Program

Output Stream

Figure: Flow of streams

Basically streams act as an intermediary between the programs and the actual IO
devices. It performs operations of file read and write.
2.2 CONSOLE (INPUT/ OUTPUT) STREAM CLASSES

It basically covers istream called input stream and ostream called output stream.
Most important is iOS which is the base of all. The class’s istream and ostream are
bases of iostream (both input and output).
Class ios provides basic support for formatted and unformatted I/O operations.
Class istream provides basic support for formatted and unformatted input operations.
Class ostream provides basic support for formatted and unformatted output
operations.
Following figure illustrates I/O stream classes, also called console stream classes.

ios

istream ostream

iostream

ifstream ostream
fstream

Figure: I/O streams

Details about various stream classes linked with console

▪ ios (General input/output stream class)


❖ It contains basic facilities that are used by all other input and output classes.
❖ It also contains a pointer to a buffer object (streambuf object).
❖ It declares constants and functions that are necessary for handling formatted input
and output operation.
▪ istream(input stream)
❖ It inherits the properties of ios
❖ It declares input functions such as get (), getline () and read ().
❖ It contains an overloaded extraction operator.
▪ ostream(output stream)
❖ It inherits the properties of ios
❖ It declares output functions such as put() and write().
❖ It contains an overloaded initiation operator.
▪ iostream(input/output stream)
❖ It inherits the properties of ios istream and ostream through multiple inheritance
and thus contains all the input and output functions.

Basic I/O
There are two basic streams which are parts of the I/O stream library and these are cin and
cout.
These are also called:
❖ Stream insertion using << with cin.
❖ Stream extraction using >> with cout.

2.3 FOUR PREDEFINED STREAMS IN C++


1. cin
2. cout
3. cerr
4. clog
Details about streams

S.No. Name of Stream Description


1 cin Is an object of the class ‘istream’ and is connected to
the standard input device (keyboard).

2 cout Is an object of the class ‘ostream’ and is connected to


the standard output device (monitor).
3 cerr Is an object of type ‘ostream’ and is connected to the
standard error device. Output through ‘cerr’ is
unbuffered (i.e. the output will appear immediately on
the screen).
It is used to inform the user about some error that
has occurred.
4 clog Is similar to the ‘cerr’ object and is also an object of
type ‘ostream’ but ‘clog’ is buffered (i.e. output will be
held in the buffer till the buffer becomes full or till the
buffer is flushed.
CIN and COUT streams in detail
Stream cin (Also called standard input stream): It is used to accept the input coming
from the input device. In programming, the keyboard is one important input device.
For formatted input operations, cin is used together with the extraction operator,
which is written as >> (i.e., two "greater than" signs).
This operator is then followed by the variable where the extracted data is stored.
For example:
int rollno; //statement 1
cin>>rollno; //statement 2

In above block, statement 1 declares a variable of type int called rollno.


Statement 2 extracts from cin a value to be stored in it.
This operation makes the program wait for input from cin; generally, it means that the
program will wait for the user to enter some sequence of integer flow from the
keyboard.
Extractions on cin can also be chained to request more than one input streams of data
in a single statement:
cin>> rollno >> phoneno;
This is equivalent to:
cin>>rollno;
cin>>phoneno;
Stream cout (Also called standard output stream): It is used to show the output
coming from a program on an output device. In programming, a monitor is one
important output device.
For formatted output operations, cout is used together with the insertion operator,
which is written as << (i.e., two "less than" signs).
This operator is then followed by the variable which will print value. For example:
int rollno = 20; //statement 1
cout<<rollno; //statement 2

In above block, statement 1 initializes a variable of type int called rollno with value 20.


Statement 2 will print it on the output screen.
Insertion on cout can also be chained to show more than one output streams of data
in a single statement:
cout<< rollno << phoneno;
This is equivalent to:
cout<<rollno;
cout<<phoneno;

2.4 INPUT/OUTPUT USING OVERLOADED OPERATORS >> (EXTRACTION


OPERATOR) AND << (INSERTION OPERATOR)

It is also called I/O operator overloading in C++.


Here, I/O means input and output streams.
It uses stream extraction operator >> to accept built-in data types as input and uses
stream insertion operator << to output the built-in data types.
The insertion and stream extraction operators can also be overloaded to perform input
and output for user-defined types like an object.
It is essential to make operator overloading function a friend of the class because it
would be called without creating an object.
Following C++ program demonstrates overloading of << and >> operators.

#include<iostream.h>
#include<conio.h>
class over
{
private:
Int a;
public:
over ( )
{
}
friend istream & operator >> (istream &in, over &ob);
friend ostream & operator << (ostream &out, const over &ob);

}; //class closed
istream & operator >> (istream &in,  over &ob)
{
    cout << "Enter Value of number”;
    in >> ob.a;
    return in;
}
ostream & operator << (ostream &out, const over &ob)
{
    out << ob.a;
   return out;
}
int main()
{
   over o1;
   cin >> o1;
   cout << " \n The Value of number is ";
   cout << o1;
   return 0;
}
Output
Enter Value of number 30
The Value of number is 30
Advantages of Stream Classes:
▪ Stream classes have good error handling capabilities.
▪ These classes work as an abstraction for the user that means the internal
operation is encapsulated from the user.
▪ These classes are buffered and do not use the memory disk space.
▪ These classes have various functions that make reading or writing a sequence of
bytes are easy for the programmer.

2.5 FORMATTING USING IOS CLASS FUNCTIONS AND FLAGS

In C++, formatting output is possible in different ways and formatting using ios class
functions and flags is one of the ways for formatting console operations performed on
Input and Output. Also manipulators are helpful for performing formatting of I/O
streams.
There exist various ios functions called ios format functions which are as mentioned
below.
1. width ()
2. fill ()
3. precision ()
4. setf ()
5. unsetf ()
Functions 1 to 3 are used for formatting ios (input/output stream) and functions 4
and 5 are used as formatting flags.
Details about above mentioned format functions of ios:
1. width ()
It defines the width of a field.
Field is what we want to print on the output screen and write with cout.
It is a kind of output function.
It is used as:
cout.width (w); //w = any integer value which will define width of field
The output printed is right-justified in this case that means towards the right side.
Example:
cout.width (7);
cout<<12;
Output:

2. Fill ()
Also known as filling and padding.
The width function adds white spaces as decided by the width of the field.
Fill () is used to fill the unused positions by any desired character.
It is also a kind of output function.
It is used as:
cout.fill (ch);
//ch is any character used to fill white spaces added by width function
Example:
cout.fill (‘*’);
cout.width (7);
cout<<12;
Output:
* * * * * 1 2

3. Precision ()
As standard for printing floating values are six digits after the decimal point. But, with
the help of precision () function, we can specify the number of digits to be displayed
after the decimal point when dealing with float values.
It is used as:
cout.precision (x);
Example:
cout.precision (3);
cout<<1.2455555;
Output:
1.25

4. Setf ()
It is a member function of ios class and known as set flags.
It is used as:
cout.setf (argu1, argu2)
//argu1 and argu2 are used for setf () function as its arguments.
It is same as following for width ():
cout.setf (ios::left, ios::adjustfield)
Argu1: formatting flag existing in ios and
Argu2 is a bit field which specifies the group to which the formatting flag belongs.
Make sure that argu1 should be one of the group members of the argu2.
It is used in following situations like:
As we know width () is right justified but what to do if the user wants to print output
as left justified.
So, in such cases- setf () is helpful.
Example:
cout.fill (‘*’);
cout.setf (ios::left, ios::adjustfield);
cout.width (7);
cout<<12;
Output:
1 2 * * * * *

Table below gives details about different setf () formats.


S. Argu
Argu2 If format required as
N 1
(bit-field) below
o. (flag)
ios::l ios::adjus
1 Left-justified output
eft tfield
ios::
ios::r
2 adjustfiel Right-justified output
ight
d
ios::i ios::
Allpy padding after
3 ntern adjustfiel
sign/base
al d
ios::s
ios::floatf
4 cienti Scientific notation
ield
fic
ios::fi ios::floatf
5 Fixed-point notation
xed ield
ios::o ios::basef
6 Octal base
ct ield
ios::d ios::basef
7 Decimal base
ec ield
ios::h ios::basef
8 Hexadecimal base
ex ield
Table: Flags for setf () function
Even there exists some flags in C++ which are also used with the setf () function of ios
class as formatting but only with argu1.
Table below gives detail about those flags used with ios for formatting which are not
having argu2.

S. Argu1 Meaning
N (flag)
o.
1 ios::show Use base indication on output
base
2 ios::show Print + before positive numbers
pos
3 ios::show Show trailing decimal point and zeroes
point
4 ios::uppe Use uppercase letters
rcase
5 ios::skip Skip white spaces on input
ws
6 ios::unit Flush all streams after insertion
buf
7 ios::stdio Flush stdout and stderr after insertion
Table: Flags without bit-fields

2.6 FORMATTING USING MANIPULATORS


Manipulators are operators used in C++ for formatting output.
C++ offers the several input/output manipulators for formatting.
These are functions specifically designed to be used in combination with the insertion
(<<) and extraction (>>) operators on streams.
For example: Manipulators are used to change formatting parameters on streams and
to insert or extract certain special characters.
These are basically helper functions that make it possible to manage input/output
streams.
Header file <iomanip> is used to work with manipulators. Few manipulators work even
without adding this header file.
For example: endl (end line manipulator) works even if the <iomanip> header file is
missing. Overall, this header file contains information useful for performing formatted
I/O with parameterized stream manipulation.
These can be categorized as:
Input manipulators, output manipulators, both input/output manipulators and
parameterized manipulators.
Parameterized manipulators require the explicit inclusion of the header file <iomanip>.
List of various manipulators as given below
1. endl
2. dec, oct, hex
3. setbase
4. setw
5. setfill
6. setprecision
7. ends
8. ws
9. flush
10. setiosflags
11. resertiosflags
From these manipulators:
▪ ws is input manipulator.
▪ endl, ends, flush are output manipulators.
▪ setbase, setfill, setprecision, setw, setiosflags, resetiosflags are parameterized
manipulators.
▪ Numerical base format flags also called “basefield” flags. These are used fin same
way as output manipulators used.
Details about above mentioned manipulators:
1. endl
Its full form is endline.
Basically it is the line feed operator in C++.
Its purpose is to feed the whole line and then point the cursor to the beginning of the
next line. We can use \n (\n is an escape sequence) instead of endl for the same
purpose.
It is an output manipulator as used with cout stream.
Example:
#include <iostream>
using namespace std;
int main()
{
cout<<"WELCOME-----"<< endl<< "IN C++";
return 0;
}
Output
WELCOME-----
IN C++
2. oct, dec, hex
These are helpful to convert a value into a specific base like:
▪ Dec will convert value into decimal point having base 10.
▪ Oct will convert value into octal having base 8.
▪ Hex will convert value into hexadecimal having base 16.
It is an output manipulator as used with cout stream.
Example:
#include <iostream>
using namespace std;
int main()
{
int a=12;
cout<<oct<<a<<endl;
cout<<dec<<a<<endl;
cout<<hex<<a<<endl;
return 0;
}
Output
14
12
c
As shown above:
Value 12 becomes 14 in base octal and becomes c in base hexadecimal.
3. Setbase
It is a parameterized manipulator but used like output manipulator.
It works similarly like above but the way of using this manipulator is different from the
above one. In this, base is not applied as oct, dec, hex but setbase is
used as a function with one argument.
Argument passed to setbase is as:
▪ 8 for getting output corresponds to a valid number in base octal.
▪ 10 for getting output corresponds to a valid number in base decimal.
▪ 16 for getting output corresponds to a valid number in base hexadecimal.
Example:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a=12;
cout<<setbase(8)<<a<<endl;
cout<<setbase(10)<<a<<endl;
cout<<setbase(16)<<a<<endl;
return 0;
}
Output
14
12
c

4. Setw
It is a set field width manipulator.
It is a kind of manipulator which is used to set the width that a particular value will
consume. It is a parameterized manipulator but used like an output manipulator.
The total spaces consumed by a variable are equal to the argument value passed to setw ()
like: setw (10) has total spaces =10.
So, if the value is of only 2 characters then the remaining 8 spaces will be blank spaces
called white spaces. The white spaces will be from the left side as it is right justified so
contents i.e. value will consume spaces from the right side. It is also an output
manipulator and use of the header file “iomanip” is mandatory for it.
Example:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a=10, b=786;
cout<< setw (5) << a << setw (5) << b;
return 0;
}
Output
1 0 7 8 6

As shown above, three blank spaces also called white spaces before the value of a (i.e.
10) are printed and two white spaces before the value of b (i.e. 786) is printed. The
reason is: a itself is of 2 characters but b is of three characters.so:
For variable a, blank spaces are 5 minus 2 equals 3.
For variable c, blank spaces are 5 minus 3 equals 2.
5. setfill
It is a parameterized manipulator but used like an output manipulator.
It is a set fill manipulator used to fill empty/unused white spaces that were added to a value
by using setw () manipulator. It allows users to use any symbol to fill unused spaces.
The argument value passed to setfill() should be any symbol.
It is used in combination with setw () as it is having an impact on setw ().
Its syntax is: setfill (char c).
Example 1: Use same symbol to fill all empty spaces in whole program
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a=10, b=786;
cout<<setfill (‘+') << setw (5) << a << setw (5) << b;
return 0;
}
Output
+ + + 1 0 + + 7 8 6

Example 2: Use different symbols to fill empty spaces in the program.


Use Turbo C++ IDE in following example:
#include <iostream.h>
int main()
{
int a=10, b=786;
cout<<setfill (‘+’)<< setw (5) << a;
cout<<setfill (‘*’)<< setw (5) << b;
return 0;
}
Output
+ + + 1 0 * * 7 8 6

6. Setprecision
It is also a parameterized manipulator but used like an output manipulator.
It is used to control the number of decimal digits of a float value which will be
displayed on the output screen.
As standard for printing floating values are five digits after the decimal point. But,
with the help of setprecision () manipulator, we can specify the number of digits to be
displayed after the decimal point when dealing with float values.
Example:
#include <iostream>
#include <iomanip> //mandatory
using namespace std;
int main()
{
float a=10, b=3;
float c=a/b;
cout<<setprecision (3) << c;
return 0;
}
Output:
3.33
As shown above, instead of output 3.33333,
The round figure after decimal is only 2 digits because the argument value passed to
setprecision is 3.
7. Ends
Full name of this manipulator is end of string. It inserts null character at the end of a string
to show its termination. It is also one of the important output manipulators.
There is one difference as it succeeds the string on which i.e. applied after string is printed as
shown below:
Example:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a=10;
cout<<a << ends;
return 0;
}
Output
10
Ends written after “a“means string is terminated here.
8. Ws
Full name of this manipulator is white space.
It is an input manipulator.
It is used to ignore the leading white spaces that are succeeding the first field.
So, it will print the typed or input string till the first blank space i.e. printing on the output
screen till any white (empty/blank) space comes.
Example:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
char pwd [15];
cout<< "Enter password::” ;
cin>> ws >> pwd;
cout << endl << "After applying ws on pwd – output is ----- "<< pwd;
return 0;
}
Output:
Enter password:: KEVI @ 123
After applying ws on pwd – output is ----- KEVI
As shown in above example- first white space came after KEVI and before @.
So, the manipulator has ignored all characters leading after this white space.
9. Flush
▪ It is an output manipulator used as a flush cleaner buffer.
▪ Its behaviour as a manipulator is equivalent to calling OS's member function flush.
▪ The flush member function is used to cause the stream associated with the output
to be completely emptied.
▪ The argument of flush takes no input parameters whenever it is invoked.
▪ For input on the screen, this is not necessary because all output is flushed
automatically. However, in the case of a disk file being copied to another, it has to
flush the output buffer prior to rewind the output file for continued use.
▪ The function flush ( ) does not have anything to do with flushing the input buffer.
Used as:
cout.flush ( );
//Example using flush member function
//it is executed in online g++ compiler of C++
#include <iostream>
using namespace std;
int main()
{
cout <<" Hello in the World of C++ \n";
cout << " This is my loving subject \n";
cout . flush ( ) ;
return 0;
}
Output
Hello in the World of C++
This is my loving subject
10. Setiosflags
The setiosflags manipulator function is used to control different input and output
settings. The I/O stream maintains a collection of flag bits.
The setiosflags manipulator performs the same function as the setf function.
The flags represented by the set bits in f are set.
The general syntax of the setiosflags is: setiosflags ( long h)

Example using setiosflags of basefield:


#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int value;
cout << "enter a number ";
cin >> value;
cout<< "hexadecimal = ";
cout <<hex <<setiosflags (ios:: showbase) << value << endl ;
return 0;
}
Output
enter a number10    
     hexadecimal = 0xa
11. Resetiosflags
The restiosflags manipulator performs the same function as that of the resetf function. The
flags represented by the set bits in f are reset.
The general syntax of the resetiosflags is: resetiosflags (long f) 
// Example using resetiosflags
// Write code in Code Blocks editor and press the "Run" button to execute it.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << hex << setiosflags (ios::showbase);
cout << 100 << endl;
cout << resetiosflags(ios::showbase) << 100 << endl;
return 0;
}
Output
0x64
64
This code first sets the showbase flag and then resets it using the resetiosflags manipulator. 

◆◆◆◆◆
Chapter 4
Constructors & Destructors
5.1 CONSTRUCTORS

A constructor is a special member function of a class which is automatically executed


when an object of that class is created.
The Compiler calls the Constructor whenever an object is created.

Special characteristics of Constructor


▪ It has same name as of class.
▪ It must be a public member means in public section.
▪ No return type, not even void.
▪ It is automatically invoked when the objects are created.
▪ It cannot be inherited; still derived class can call the base class constructor.
▪ Like other functions, it can have default arguments.
▪ We cannot refer to its address.
▪ Virtual constructor can’t be created.

How to define constructor in a class


Constructors can be defined either inside the class definition or outside class
definition.
Constructor defined inside the class as shown below:
class A
{
int x;
public:
A ( ) //Constructor defined inside the class
{ }
};
Constructor defined outside the class using class name and scope resolution (::)
operator as shown below:
class A
{
int x;
public:
A(); //Constructor declared
};
A::A( ) // Constructor definition
{
x = 20;
}

5.2 DESTRUCTOR
A destructor is a special member function of a class which destroys the object as soon
as the scope of object ends.
The destructor is called automatically by the compiler when the object goes out of
scope.
The syntax for destructor is same as that for the constructor, the class name is used
for the name of destructor; with a tilde~ sign as prefix to it (add ~ before destructor).
Destructors will never have any arguments.
As mentioned below, destructor is created inside the class:
class A
{
public:
~A( );
};
The following restrictions apply to both constructors and destructors:
▪ Constructors and destructors do not have return types nor can they return values.
▪ References and pointers cannot be used on constructors and destructors because
their addresses cannot be taken.
▪ Constructors and destructors cannot be declared static, const, or volatile.
▪ Unions cannot contain class objects that have constructors or destructors.

Need for constructors and destructors


As the compiler automatically calls constructors when defining class objects and calls
destructors when class objects go out of scope. So, both of these plays an important
role in C++ programming by adding more flexibility.
So, when we create an object, its constructor body will be invoked itself whereas
calling a function (method) is always optional.
During cleanup, a destructor may release objects allocated by the corresponding
constructor.
5.3 TYPES OF CONSTRUCTOR
Constructors are of three types:
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor

1. Default Constructor

Default constructor is the constructor which doesn't take any argument. It has no
parameter.
Syntax:
class_name ()
{
Constructor Definition
};
//Example illustrating use of default constructor :
#include <iostream>
using namespace std;

class A
{
int rno;
public:
A( ) // A ( ) is default constructor as having no argument in parenthesis
{
rno=10;
cout<<rno;
}
};

int main()
{
A ob;

return 0;
}

Output
10
In this case, when object ob is created the constructor is called which initializes its
data members (rno with value 10).
If in case, a default constructor is not defined by programmer then compiler provides
default constructor implicitly.
//Another example illustrating use of default constructor:
#include <iostream>
using namespace std;
class A
{
public:
int rno;
};

int main()
{
A ob;
cout << ob.rno;
return 0;
}

Output
0
In this case, default constructor provided by the compiler will be called which will
initialize the object data members to default value that will be 0 in this case.

2. Parameterized Constructor
These are the constructors with parameter like: A (int i, int j) .
A is name of constructor, i and j are two variables of integer data type.
//Class with parameterized constructor:
class A //A is class name
{
public:
A (int i , int j ) // A is parameterized constructor
}

Using this Constructor, it is easy to provide different values to data members of


different objects, by passing the appropriate values as argument (parameter).
//Example using concept of parameterized constructor:
#include <iostream>
using namespace std;
class A
{
public:
int rno;
A(int i)
{ //parameterized constructor
rno = i;
}
void show ( )
{
cout<< "Roll number is "<<rno;
}
};
int main()
{
A o1(162);
o1. show ();
return 0;
}
Output :
Roll number is 162

By using parameterized construcor as in above case, we have initialized one object


with user defined value 162.
We can have any number of parameters in a constructor. Also we can initialize any
number of user defined objects.

3. Copy Constructor

In C++, one constructor can be copied into another one. Basically, it is used to copy
one object into other for a class. It creates a copy of an already existing object. It
occurs for a class type.
It is usually of the form A ( A& ), where A is the class name.
The compiler provides a default Copy Constructor to all the classes.
Syntax:
Classname( const classname & objectname )
{
....
}
In this process, pass reference of object as an argument to constructor.
Let con is name of class, so same is name of constructor. Then, use concept of copy
constructor as:
{
con ( con& ob1)
{ A = ob1. A; }
}
Inside main () ,
con o1;
con o2 ( o1 ) ; // copy constructor concept.
As mentioned above, reference operator is used which is helping to pass value from
one object to another.
//C++ example illustrating use of copy constructor
#include <iostream>
using namespace std;
class con
{
int a;
public:
con (int x )
{
a = x;
cout<<" Value before copying "<<a;
}
con ( con & ob1)
{
a = ob1. a;
cout<<"\n Value after copying "<<a;
}
};
int main ()
{
con o1 (5);
con o2 ( o1 );
return 0;
}
Output
Value before copying 5
Value after copying 5

5.4 CONSTRUCTOR OVERLOADING

▪ It is also called many constructors in one class or constructor in multiple forms.


▪ In C++, it is possible to overload a constructor by declaring it in more than one
form.
▪ It is quite similar to function overloading.
▪ It is possible in following conditions:
(a) Depending upon number of arguments of constructors
(b) Depending upon return type of arguments of constructors.
It means, overloaded constructor has same name but different number of arguments
or type of arguments.
Let con is name of class, so same is name of constructor:
Then it can be overloaded according to point (a) mentioned above,
con (int)
con (int, int)
con (int , int, int)
Same for float, char, double etc.
According to point (b) mentioned above, constructor named “con” can be overloaded
as:
con (int)
con (float)
con (char)
Also following expresses constructor overloading.
con (int, float)
con (int, float, double)

#include<iostream>
using namespace std;
class con
{
int a, b; // Variable Declaration
public:
con() //Constructor without parameters
{ // Assign Values in Constructor
a = 50;
b = 60;
cout << "\nIn Constructor without parameters";
}
con(int x, int y) //Constructor with parameters
{ // Assign Values In Constructor
a = x;
b = y;
cout << "\nIn Constructor with parameters";
}
void display()
{ cout << "\nValues are: " << a << "\t" << b;
}
};
int main()
{
con Ob1;
Ob1.display();

con Ob2(10, 20);


Ob2.display();
return 0;
}
Output
In Constructor without parameters                                                                          
Values are:   50        60                                                                                            
In Constructor with parameters                                                                              
Values are:   10        20  

5.5 DYNAMIC CONSTRUCTOR


It is a process of allocating the memory to the objects at the runtime.
It is also called a process of initializing objects dynamically.
It uses ‘new’ operator.
//Example illustrating the use of dynamic constructor
#include <iostream>
using namespace std;
class con
{
int * p;

public:
con ( )
{
p = new int;
*p = 20;
}
void show ()
{
cout<< "The value of pointer variable is "<< *p;
}
};
int main ( )
{
con o1;
o1. show ( );
return 0;
}
Output
The value of pointer variable is 20
As shown in above example, a class named con has pointer type variable declared in
it. Also using new operator, memory is allocated to it inside the code of constructor
dynamically.

5.6 EXPLICIT CONSTRUCTOR


▪ A constructor can be created as explicit constructor by using keyword “explicit”
before it.
▪ It is also called constructor conversion.
▪ It can only be used during declaring constructors within a class declaration.
▪ It avoids implicit call to the constructor.
▪ Basically explicit constructor controls unwanted implicit type conversions.
▪ Firstly look the concept of implicit constructor as executed by following example
and then in further example, use and benefit of explicit constructor will be easy to
understand.
//Example illustrating the Concept of implicit call
#include <iostream>
using namespace std;
class ABC
{
int x;
public:
ABC (int a)
{
x = a;
cout<<"\n Value by Construcor\t" << x ;
}
};
int main()
{
ABC ob1 (10); // Normal call to constructor
ABC ob2 = 20; // implicit call to constructor
return 0;
}
Output:

Value by Construcor 10
Value by Construcor 20
Here, class name is ABC and ob1, ob2 are its objects.
According to statement:
ABC ob2= 20
Value 20 is initialized to object ob2 of ABC but the point to notice here is, ob2 is object
of type base but 20 is of type integer. So, question is how it can be done. Such
conversion is called constructor conversion i.e. implicit conversion. To avoid this, use
explicit keyword with constructor as:
explicit ABC (int x)
So, the explicit constructor is helpful to control unwanted implicit type conversions.
Use it within a class declaration.
ABC ob = 20; is legal and is same as ABC ob1 = con (20).

If explicit keyword is used then assigning a value like ABC ob = 20 is illegal but
passing value explicitly through con ob = con (20) is legal.

Example: Use of Explicit Example: Use of Explicit


keyword in C++ program but Constructor in legal way:
in illegal way:
#include <iostream>
#include <iostream> using namespace std;
using namespace std; class ABC
class ABC {
{ int x;
int x; public:
public: explicit ABC (int a)
explicit ABC (int a) {
{ x = a;
x = a; cout<<"Value by constructor\t" <<
cout<<"Value by constructor\t" x;
<< x ; }
} };
}; int main()
int main() {
{ ABC ob = ABC (30);
ABC ob = 30; return 0;
return 0; }
}
Output: compiler error Output:
In function 'int main()': Value by constructor 30
error: conversion from 'int' to
non-scalar type 'ABC' requested
ABC ob = 30;
As the output of above two examples explain better, if explicitly a value will be allotted
to the constructor of a class then the compiler will generate error. But if the same
allocation will be done as shown in example on the right side then it is correct.

Constructors and destructors with static members


In C++, it is possible to declare members of a class of type static which can be easily
accessed by constructor and destructor.
It means, at a time only one copy of a static data member will be generated for the
whole class. So, any operation in the constructor and destructor body is possible to
perform which is using static data member.
//Example illustraing construtor and destructor using static members in a class
#include <iostream>
using namespace std;
class con
{private:
static int s =0;
public:
con ( )
{
s++;
cout<<"\n Static Value is "<< s;
}
~ con ( )
{
--s ;
cout<<"\n Now static value of s is " << s;
}
};
int con :: s; //compulsary to add
int main ( )
{
con o1, o2, o3;
cout<<"\n Used static data ";
return 0;
}
Output
Static Value is 1
Static Value is 2
Static Value is 3
Used static data
Now static value of s is 2
Now static value of s is 1
Now static value of s is 0
Explanation of above example:
As mentioned above, if following statement will not be written
int con :: s;
Then, compiler will generate error that type and scope of “s” is undefined.
Both constructor and destructor are using static variable.
Constructor is incrementing value of “s” and destructor is decrementing its value.
Three objects are created for con class. So, constructor and destructor are called three
times.

5.7 MEMBER INITIALIZER LIST WITH CONSTRUCTOR

▪ It is also called member initialization list.


▪ C++ provides a method for initializing class member variables (rather than
assigning values to them) via a member initializer list.
▪ It uses colon and comma operators.
▪ Colon operator is helpful to initialize each variable that is listed with constructor as
following:
con ( int x) : rollno (x);
Here value of x will come from value passed in main ( ) through object of class like:
main ( )
{
con o1 (20);
▪ This value 20 will be passed to variable rollno.
▪ If more than one element in list then use comma as:
con ( int x, int y) : rollno (x), sem (y);
Here, value for x and y will be passed to object of parameterized constructor
with two parameters of integer type.
Let in main ( ), for variable x, value passed is 30 and for variable y is 3.
Then variable rollno will get value 30 and sem will get 3.
//Example illustrating the use of member initialization list.
#include <iostream>
using namespace std;
class list
{
int rollno, sem;
public:
list (int x, int y ) : rollno ( x) , sem (y )
{ }
void show ( )
{
cout<< " Rollno and Semester record is "<< rollno<< "\t" << sem ;
}
};
int main ( )
{
list obj (30 , 3);
return 0;
}
Output:
Rollno and Semester record is 30 3
Suppose we are given the C++ code below. For such types of codes, what would be
printed and in what order output will be printed is the main concern.
In such a case, we will have to be aware of the execution order of the constructor and
destructor in inheritance.
//Example illustrating order of execution of constructor and destructor
#include <iostream>
using namespace std;
class Base
{
public:
Base ( )
{
cout << "Inside Base constructor" << endl;
}
~Base ( )
{
cout << "Inside Base destructor" << endl;
}
};
class Derived : public Base
{
public:
Derived ( )
{
cout << "Inside Derived constructor" << endl;
}
~Derived ( )
{
cout << "Inside Derived destructor" << endl;
}
};
int main( )
{
Derived x;
return 0;
}
Output
Inside Base constructor                                                                                           I
nside Derived constructor                                                                                  
Inside Derived destructor                                                                                   
Inside Base destructor 
Here the main point about execution order of the constructor and destructor is what
will be printed out in the program above, and in what order.
Basically, it's a test to see if you know in what order the constructors and destructors
will be called when a program deals with inheritance.
The order of calling is:
1. Base class constructor
2. Derived class constructor
3. Derived class destructor
4. Base class destructor
In the code above, when the object "x" is created, first the Base class constructor is
called, and after that the Derived class constructor is called. Because the Derived
class inherits from the Base class, both the Base class and Derived class constructors
will be called when a Derived class object is created.
When the execution of the main function is finished, the object x's destructor will be
called first, and after that the Base class destructor will be called.
So, here is what the output of the code above would look like:
Output
Inside Base constructor
Inside Derived constructor
Inside Derived destructor
Inside Base destructor

◆◆◆◆◆
Chapter 5
Operator Overloading
& Type Conversion
6.1 OPERATOR OVERLOADING
It is one of the features of C++.
As the term overload means use one thing more than once.
Same is case of operator overloading which says:
Pick an operator (Let plus (+) operator and then overload it by performing different
operations on it as following:
▪ + can be used for adding two integers as 10 + 20
▪ + can be used to add two strings as “Hello” + “world” called concatenation
operation.
▪ + can be used to add two float values as 5.6 + 4.4
Yet it is not completely operator overloading in C++.
So, operator overloading of + operator is complete with following:
▪ + can be used to add two objects as obj1 + obj2. These objects should refer to a
class.
So, its Syntax is:
Return-type class-name: operator operator-symbol ( arguments)
{
}

List of overloading operators


Operator Symbol Type of Operator
● + (addition)
● - (subtraction) Arithmetic operators
● * (multiplication)
● / (division)
● % (modulus)
● ^ (XOR)
● | (OR)
● & (AND)
Bitwise operators
● ~ (complement)
● << (shift left, insertion to stream)
● >> (shift right, extraction from stream)
● == (equality)
● != (inequality)
● > (greater-than)
Relational operators
● < (less-than)
● >= (greater-than-or-equal-to)
● <= (less-than-or-equal-to)

● ! (NOT)
● && (AND)
Logical operators
● || (OR)

● += (addition-assignment)
● -= (subtraction-assignment)
● *= (multiplication-assignment)
● /= (division-assignment)
Compound assignment
● %= (modulus-assignment)
operators
● &= (AND-assignment)
● |= (OR-assignment)
● ^= (XOR-assignment)
● <<= (shift-left-assignment)
● >>= (shift-right-assignment)
● ++ (increment) Increment and decrement
● -- (decrement) operators
● new (allocate memory for object)
● new[ ] (allocate memory for array)
Memory management operators
● delete (deallocate memory for object)
● delete[ ] (deallocate memory for array)
● , Comma operator
● -> ( ) Member access operators
● ->* ( )
● () Function call operator
● [] Subscript operator

Operators which cannot be overloaded in C++


Following is list of six C++ operators which cannot be overloaded.
S.No. Operator Symbol Type of Operator
1 ?: Conditional Operator
2 . (dot) member selection
3 .*  member selection with pointer-to-
member
4 ::  scope resolution
5 sizeof object size information
6 typeid object type information

6.2 RULES FOR OVERLOADING OPERATORS

Following are some important rules which a programmer should follow while
overloading an operator:
▪ Only existing operators can be overloaded.
▪ Overloaded operators follow the syntax rules of the original operators. They cannot
be overridden.
▪ The overloaded operator must have at least one operand that is of user defined
type.
▪ We cannot change the basic meaning of an operator. It means, we cannot redefine
the plus (+) operator to subtract one value from the other.
▪ There are some operators that cannot be overloaded like size of operator (sizeof),
membership operator (.), pointer to member operator(.*), scope resolution
operator(::), conditional operators(?:) etc.
▪ We cannot use “friend” function to overload certain operators. However, member
function can be used to overload them. Friend Functions cannot be used with
assignment operator (=), function call operator (( )), subscripting operator([n]), class
member access operator (->) etc. 
▪ When using binary operators overloading, the left hand operand must be an object
of the relevant class.
▪ Binary arithmetic operators such as +,-,* and / must explicitly return a value. They
must not attempt to change their own arguments.

6.3 OVERLOADING OF VARIOUS OPERATORS

6.3.1 Overloading Unary Operators


There are two important unary operators called increment and decrement operators.
Symbol of increment operator is ++ and symbol of decrement operator is --.
As unary operators take only one operand (data value). This operand can be on left
side of operator or it can be on right as:
a++ ------------- (1)
++ a ------------- (2)
If ++ is after variable as in expression (1) then called post increment.
If ++ is on left side of variable as in expression (2) then called pre increment.
Same is case of decrement operator.
b -- ------------- (3)
-- b ------------- (4)
Expression (3) indicates post decrement and expression (4) indicates pre decrement of
b variable.
To overload unary increment (++) and decrement (--) operators,
The method differs only with argument of operator operator-symbol ( ).
Inside class, use syntax:
void operator ++ ( ) for pre increment and 
void operator ++ ( int) for post increment.
voidoperator -- ( ) for pre decrement and  
void operator --( int) for post decrement.
Example written below can clear the overloading of unary increment operator.
//C++ program for overloading unary pre increment (++) operator
#include<iostream>
using namespace std;
class overl
{
private: int a;
public:
void get ( )
{
cout<< "enter number ";
cin >> a;
}
void operator ++ () //unary ++ operator overloading
{
++ a ; //pre increment
}
void show ( )
{
cout << " value of a is: " << a;
}
}; // class closes here
int main()
{
overl o1;
o1. get ( ) ;
++o1 ;
cout << " after pre increment - >";
o1. show ( );
return 0;
}
Output
enter number 10
after pre increment - > value of a is: 11

Explanation of above program


In above code, overl is name of class which is user defined.
About class code, in class overl: one data member has been taken as private which is
of integer type and its name is ‘a’.
There are three member functions in public section:
get ( ),
operator ++ () and
show ( ).
Here, get ( ) is taking value from user. Then, one function code is mentioned for
overloading ++ operator. It is simple with code of just doing same operation as the
operator indicates.
So, ++a is mentioned here which is basically performing pre increment of variable a.
same is for a++.
The next member function of overl class is show ( ) which is simply showing value of
variable on output screen.
Now it depends on how these member functions are called in main ( ).
In main ( ), o1 is an object created for overl class.
Next, o1.get( ) means: calling of get () member function of class overl as o1 is also of
class overl.
So, ‘enter number’ and then cursor waiting for user to type something. Let user has
entered 10.
As in main ( ), next statement after ‘o1.get ( )’ is ‘++ o1’ which is very important and
main statement of operator overloading. It is pre increment operator overloading. Now,
when compiler will read this line then automatically it will jump at following code of
overl class.      
 void operator ++ ( )
        {
            ++a;
        }
There is no restriction on writing statements in function operator ++ ( ) body but
always write relevant statements which are helpful to perform overloading.

//C++ program for overloading unary post increment (++) operator


#include<iostream>
using namespace std;
class overl
{
private: int a;
public:
void get ( )
{
cout<< "enter number ";
cin >> a;
}
void operator ++ (int) //unary ++ operator overloading
{
a ++; //post increment
}
void show ( )
{
cout << " value of a is: " << a;
}

}; // class closes here


int main()
{
overl o1;
o1. get ( ) ;
o1 ++ ;
cout << " after post increment - >";
o1. show ( );
return 0;
}
output
enter number 15
after post increment - >value of a is: 16

When performing post increment then if in case no argument is passed to operator ++


( ) function then it shows compiler error like:
‘no 'operator++(int)' declared for postfix '++' ‘.
So, it is clear that for pre operation, no need of argument of operator functions but for
post, it is needed.
Unary decrement operator (- -)
Same like unary increment operator, unary decrement operator is also used in two
forms. Pre decrement and post decrement.
Following C++ examples makes it clear.
//C++ program for overloading unary pre decrement (--) operator
#include<iostream>
using namespace std;
class overl_decrement
{
private: int a;
public:
void get ( )
{
cout<< "enter number ";
cin >> a;
}
void operator -- ( ) //unary – pre decrement operator overloading
{ --a ; }
void show ( )
{
cout << " value of a is: " << a;
}
}; // class closes here
int main()
{
overl_decrement o1;
o1. get ( ) ;
--o1;
cout << " after pre decrement - >";
o1. show ( );
return 0;
}
Output
Enter number 10
after pre decrement - > value of a is: 9
// C++ program for overloading unary post decrement (--) operator
#include<iostream>
using namespace std;
class overl_decrement
{
private: int a;
public:
void get ( )
{
cout<< "enter number ";
cin >> a;
}

void operator -- (int) //unary -- overloading post decrement


{
a --;
a--;
a--;
}
void show ( )
{
cout << " value of a is: " << a;
}
}; // class closes here
int main()
{
overl_decrement o1;
o1. get ( ) ;
o1 -- ;
cout << " after post decrement - >";
o1. show ( );
return 0;
}
Output
enter number 10
after post decrement -> value of a is 7
6.3.2 Overloading Binary Operators

Same like unary operators; it is possible to overload binary operators.


Binary operators need two operands (values), one on its left side and other on its right
side.
These operators are overloaded by using two methods.
1. Overloading Binary operators using member functions (most accepted method)
2. Overloading binary operators using friend functions
Some important points about binary operator overloading:
In both methods, return type is of class type i.e. name of class.
If member function method is used then it takes only one argument which is of class
type. But in case of friend function method, it takes two arguments as class type.
It returns a class type.
Binary operators like plus, minus, multiplication, division, modulus, logical AND (&&),
bitwise AND (&). Addition assignment (+ =), less than (<), left shift assignment (<<=) etc
all can be easily overloaded in C++.

All these operators come under following three main categories:


1. Overloading of arithmetic operators
2. Overloading of comparison operators
3. Overloading of assignment operators

1. Overloading of arithmetic operators

All arithmetic operators (+, -, *, /, %) can be overloaded.


1.1 verloading of Addition (+) Binary operator
No doubt, + can add two integers like 12+8 equals to 20.
It can add two strings like “Hello” + “World” concatenates HelloWorld.
Also it can add two float numbers like 1.1+2.1 equals to 3.2 etcetera.
Still it is not overloaded.
To overload it in C++, must use plus to add two objects also like o1 + o2 equals to o3
where o1 and o2 are two objects.
Consider the following expression:
o3 = o1 + o2
This expression contains three objects namely o1, o2 and o3.
Objects o1 and o2 are the operands while o3 is the object in which the sum of o1 and
o2 is assigned.
In the above expression, the operator function is supposed to add two user defined
data types and returns a user defined data type.
Let name of class is bload which will do operator overloading of binary addition
operator (+).
Then in class bload- the code of operator + function will be as following:
bload operator + (bload obj) // bload is name of class
 And its code in class will be as following:
bload operator + (bload obj )
{
bload temp;
Code 1
temp. x = x + obj .x;
}
Since the function operator + ( ) needs to return the result, we need to have a temp
variable (of the same class type) that stores the value to be returned.
It should be noted here that in overloading binary operators, the operand to the left of
the operator is used to invoke the operator function while the operand to the right of
the operator is always passed as an argument to the function.
And for above code of class, in main () function the code will be as following:
o3 = o1 + o2;
In code 1, x (left operand of + binary operator) is data member of object o1,
obj. x (right operand) is data member of object o2 and temp.x is data member of object
o3. Now o3 will print output.
 See following examples to learn operator overloading concepts:
// C++ program to overload binary operator + (addition)
#include<iostream>
using namespace std;
class load
{
private: int a;
public:
void get ( )
{
cout<< "enter values for a";
cin>> a;
}
load operator + (load t)
{ Overloading code in class
load t1;
t1. a = a + t . a ;
return (t1);
}
void show ( )
{
cout<< "value is "<<a;
}
};
int main ( )
{
load o1, o2, o3; //o1, o2, o3 are 3 objects of class load
cout<<"For object o1:\n";
o1. get ();
cout<<"For object o2: \n";
o2. get ();
cout<<"Result by object o3 is :";
o3 = o1 + o2;
o3. show ( );
return 0;
}
Output
For object o1:
enter values for a 3
For object o2:
enter values for a 6
Result by object o3 is 9

It is easy to know about operator overloading from above mentioned program that
when two objects are added then automatically overloading code written inside the
class will be called. It is mandatory that it should contain “operator” keyword.
Another way to overload a binary operator in C++.
//C++ Program to overload + operator using member function method
#include <iostream>
using namespace std;
class complexno
{
int real, imag;
public:
complexno ( )
{ }
complexno (int x, int y)
{
real = x;
imag = y;
}
void show ()
{
cout<< real << " + i " <<imag <<endl;
}
complexno operator + (complexno c)
{
complexno c1;
c1. real = real + c . real;
c1. imag = imag + c. imag;
return (c1);
}
};
int main ( )
{
complexno o1 (10, 20);
cout<<"In a + i b form - Object o1 is : ";
o1. show ();
complexno o2 (15, 25);
cout<<"In a + i b form - Object o2 is : ";
o2.show ();
complexno o3 ;
o3 = o1 + o2;
cout<<"In a + i b form - SUM OF TWO COMPLEX NUMBERS IS : ";
o3. show();
return 0;
}
Output
In a + i b form - Object o1 is : 10 + i 20
In a + i b form - Object o2 is : 15 + i 25
In a + i b form - SUM OF TWO COMPLEX NUMBERS IS : 25 + i 45
In above program code, o3 = o1 + o2 will work as:
When this statement will execute then the code of operator function written in class
public section will be called. Object o2 which is on right part of operator symbol will be
copied into object ob which is created as argument in ‘complexno operator +
(complexno c)’ function.
Here o1 + o2 means calculate, execute complete body of operator + ( ) function.
As its body is:
complexno operator + (complexno c)
{
complexno c1;
c1. real = real + c . real;
c1. imag = imag + c. imag;
return (c1);
}
Basically object o2 is copied into object c at the time of execution.
‘c1. real = real + c . real ’ statement will find sum of real part of o1 and o2.
‘c1. imag = imag + c. imag’ will find sum of imaginary part of o1 and o2.
Real part is first argument and imaginary part is second argument.
Result to o3 is finally provided by c1 as return (c1) statement is doing.
Same like + operator, other arithmetic operators can also be overloaded as written
below.
o3 = o1 – o2;
o3 = o1 * o2;
o3 = o1 / o2;
o3 = o1 % o2;
Use friend function to overload bnary + operator:
The syntax is-
friend void operator + (complexno c, complexno d);
Above statement should be written in class body. When using friend function concept
for overloading binary operator then we need two arguments which are of object type.
First argument will help to pick values comes on left side of + and second argument
will pick value on right side of +.
T is one more object which will accept output after addition.
So, t.real will print addition of two real values of two objects and t.imag will print
addition of two imaginary values.
In main () function, two objects are created and then after passing values to both, they
are called to do binary addition.
Ultimately the code of + function will be called which is created with the help of friend
function concept.
There will be matching like- o1 with values 10, 20 will go to object c of + function and
o2 with values 15, 25 will go to object d of + function which is second argument of the
statement: void operator + (complexno c, complexno d). Finally we will get addition of
both.
This method is also an easy method to use for overloading unary, binary and other
operators which comes under the list of overloaded operators.
Following example is using one more method to overload an operator in C++.
//C++ Program to overload + operator using friend function method
#include <iostream>
using namespace std;
class complexno
{
int real, imag;
public:
complexno ( )
{ }
complexno (int x, int y)
{
real = x;
imag = y;
}
void show ()
{
cout<< real << " + i " <<imag <<endl;
}
friend void operator + (complexno c, complexno d);
}; //class closes here
void operator + (complexno c, complexno d)
{
complexno t;
t.real = c.real + d.real;
t.imag = c.imag + d.imag;
cout<<" Sum of Real Values "<<t.real;
cout<<"\n Sum of Imaginary Values "<<t.imag;
}
int main ( )
{ complexno o1 (10, 20);
complexno o2 (15, 25);
o1 + o2;
return 0;
}
Output:
Sum of Real Values 25
Sum of Imaginary Values45

In above program, friend keyword is written to allow friend function use for operator
overloading. Same program can be executed with the concept of member function.

2. Overloading of Relational/comparison operators


These are also called comparison operators because these operators compare two
values. These are also called binary operators.
There are various relational operators supported by C++ language like:
1. > symbol of greater than
2. < symbol of less than
3. >= symbol of greater than or equals to
4. <= symbol of less than or equals to
5. == symbol of is equals to
6. != symbol of not equals to
We can overload any of these operators, which can be used to compare the objects of a
class.
These operators return Boolean value which can be true or false.
So, return type of all relational operators is always bool.
Bool is one of the new data type added in C++ISO/ANSI standard library as a basic
datatype.
Syntax is:
bool b1 = true; // declaring a boolean variable b1 with true value
In C++, the data type bool has been introduced to hold a Boolean value, true or false
and the default numeric value of true is 1 and false is 0.
Following eaxmples will make concept clear:

//C++ program to overload less than (<) operator.


#include <iostream>
using namespace std;
class ABC
{
int a;
public:
ABC (int x)
{
a = x;
}
bool operator < (ABC t) // overloaded < operator
{
if(a<t.a)
return true;
else
return false;
}
};
int main()
{
ABC o1 (100), o2 (12);
if( o1 < o2 )
cout << "object 1 is less than object 2 " << endl;
else
cout << "object 2 is less than object 1 " << endl;
return 0;
}
Output
object 2 is less than object 1
The program code written above is basically comparing two values which are passed
by objects as it is concept of operator overloading.
ABC is user defined name of class.
This class has one data member named “a”.
In main ( ) function, when value 100 is passed to o1 and value 20 to o2 then it is
copied into variable “a” through parameterized constructor.
The function of operator less than (<) has one argument which is of type object named
“t”. When a < t.a will execute then 100 value of o1 object is with a and 20 value of o2
object is with t.a.
Same like < (less than) comparison operator, other relational operators can also be
easily overloaded.
Following code will overload == (is equals to) operator.
//C++ program to overload == (is equals to ) relational operator
#include <iostream>
using namespace std;
class ABC
{ int a;
public:
ABC (int x)
{
a = x;
}
bool operator ==(ABC t)
{
if(a== t.a)
{
return true;
}
else
return false;
}
};
int main()
{
ABC o1 (100), o2 (200);
if( o1 == o2 ) {
cout << "Same values passed to both objects " ;
} else {
cout << "Different values passed to both objects";
}
return 0;
}
Output:
Different values passed to both objects

3. Overloading of Assignment Operators


In C++, all assignment operators can be easily overloaded.
Various assignment operators available in C++ are:
S
y
m
b
o
l
o Name
Use of
f of Meaning of operator
opera
o operat
tor
p or
e
r
a
t
o
r
Store the value of the second
Simple
operand in the object specified by
= assign a=b
the first operand (simple
ment
assignment).
a+=b Add the value of the second
Additio
same operand to the value of the first
+ n
as: operand; store the result in the
= assign
a= object specified by the first
ment
a+b operand.
a-=b Subtract the value of the second
Subtrac
same operand from the value of the first
- tion
as: operand; store the result in the
= assign
a = a- object specified by the first
ment
b operand.
a*=b Multiply the value of the first
Multipli
same operand by the value of the second
* cation
as: operand; store the result in the
= assign
a= object specified by the first
ment
a*b operand.
/ Divisio a/=b Divide the value of the first
= n same operand by the value of the second
assign as: operand; store the result in the
a= object specified by the first
ment
a/b operand.
a%=b Take modulus of the first operand
Modulu
same specified by the value of the second
% s
as: operand; store the result in the
= assign
a=a object specified by the first
ment
%b operand.
a<<=b
same
as:
Bitwise Shift the value of the first operand
a=a<<
< left left the number of bits specified by
2
< shift the value of the second operand;
(shift
= assign store the result in the object
a by 2
ment specified by the first operand.
bits
left
side)
a>>=b
same
as:
Bitwise Shift the value of the first operand
a=a>>
> right right the number of bits specified
2
> shift by the value of the second operand;
(shift
= assign store the result in the object
a by 2
ment specified by the first operand.
bits
right
side
Bitwise a|=b Obtain the bitwise OR of the first
| OR same and second operands; store the
= assign as: result in the object specified by the
ment a=a|b first operand.
Bitwise a&=b Obtain the bitwise AND of the first
& AND same and second operands; store the
= assign as: result in the object specified by the
ment a=a&b first operand.
Obtain the bitwise exclusive OR
Bitwise a^=b
(XOR) of the first and second
^ XOR same
operands; store the result in the
= assign as:
object specified by the first
ment a=a^b
operand.

Following code will overload = (simple assignment) operator


//C++ program to perform operator overloading of = (simple assignment) operator
#include <iostream>
using namespace std;
class ABC
{
int a;
public:
ABC (int x)
{ a = x; }
void operator = (ABC t)
{
a= t.a;
}
void show ()
{
cout<<a;
}
};
int main()
{
ABC o1 (20), o2 (50);
cout<<" Value of object 1 is ";
o1.show();
cout<<" \n Value of object 2 is ";
o2.show();
o1 = o2;
cout<<"\n After assignment of o2 into o1 (o1 = o2 ) Value of object 1 is ";
o1.show ();
return 0;
}
Output
Value of object 1 is 20
Value of object 2 is 50
After assignment of o2 into o1 (o1 = o2 ) Value of object 1 is 50

Code mentioned above is easy to understand.


Class ABC is created with overloading of = operator.
So, value of o2 (which is 50) is copied into o1.

Following code will overload - = (subtraction assignment) operator in C++


//C++ program to perform operator overloading of - = (subtraction assignment)
operator:
#include <iostream>
using namespace std;
class ABC
{
int a;
public:
ABC (int x)
{ a = x; }
void operator - = (ABC t)
{
a - = t.a;
}
void show ()
{
cout<<a;
}
};
int main()
{
ABC o1 (100), o2 (30);
cout<<" Value of object 1 is ";
o1.show();
cout<<" \n Value of object 2 is ";
o2.show();
cout<<"\n After subtraction and then assignment of result into o1 (o1 -= o2 ), Value of
object 1 is ";
o1 - = o2;
o1.show ();
return 0;
}
Output:
Value of object 1 is 100
Value of object 2 is 30
subtraction and then assignment of result into o1 (o1 -= o2 ), Value of object 1 is 70

Same code can be used to overload other assignment operators by updating operator
at required places.

6.4 TYPE CONVERSION

In programming, type conversion (type casting) or type coercion are different ways
of changing an entity of one data type into another.
For example: conversion of an integer value to floating value.
If conversion is performed itself then it is called implicit conversion as mentioned
below.

//Conversion of int to //Conversion of float to int


float float f = 30.6;
int i = 20; int i = f;
float f = i;
Loss of data in this type
No loss of data as int conversion as fractional part of
contains space of 2 bytes float number will be truncated
and float has space of 4 when it will be assigned to int i;
bytes. So, such conversion
is valid.

Above type conversion is performed by compiler automatically.


Compiler does not support automatic type conversion for user defined data types. For
example, if class is involved in type conversion then follow following three methods of
type conversion.

Different types of type conversion in C++


Basically there exist three types of conversions when class involves with conversion.
1. Conversion from basic type to class type
2. Conversion from class type to basic type
3. Conversion from class type to another class type

1. Conversion from basic type to class type


In this type of typecasting, simple assignment operator (=) is used.
On left side of =, always class type and on right side of = sign, always basic data type
is mentioned.
Basic data types are inbuilt data types.
The conversion from basic type to the class type can be performed by two methods:
1. Using constructor
Method 1: Typecasting using constructor method

Must use constructor in class which is involved in typecasting as explained in


following example.

//C++ code to perform typecasting of basic type to class type


#include <iostream>
using namespace std;
class abc
{
int a;
public:
abc (int x) //constructor method used
{
a = x;
}
void show ( )
{
cout<<"Value of a : "<<a;
}
};
int main ( )
{
abc o1 (10);
o1. show ( );
int b = 50;
cout<<"\nAfter typecasting of int type to class type- ";
o1 = b;
o1.show ( );
return 0;
}
Output
Value of a : 10
After typecasting of int type to class type- Value of a : 50
Explanation of above program:
In the above program, class named “abc” is written with one int data type named “a”
and with two member functions: one is parameterized constructor and other is
function named show ( ).
In main function, object named o1 is created for this class “abc” and value 10 is
passed to it.
Automatically special member function which is constructor will be executed and
value 10 will be copied into data member “a”. Now show () function will print output
“Value of a: 10”. Then in main (), an integer variable named “b” with value 50 is taken
which is assigned to class data type as “o1 = b”.
Note that b can be of any basic data type like: float, double etc.
Now value 50 is passed to object. So, variable “a” has now 50 rather than 20. It means
o1.show () is printing output 50, not 20. This is typecasting of basic data type to class
type.
b. Typecasting using Operator Overloading:
● It is another method to achieve type conversion.
● It uses simple assignment operator (=) for this purpose.
// C++ code to perform typecasting of basic type to class type using operator
overloading method:
#include <iostream>
using namespace std;
class sample
{
float a;
public:
void operator = (float x) // overloading function
{
a = x;
}
void show ( )
{
cout<<"Value of a is "<<a;
}
};
int main()
{
sample o1;
float y =30.5;
cout<<"Using overloading method, after type conversion of basic to class type \n";
o1.operator = (y);
o1.show();
return 0;
}
Output:
Using overloading method, after type conversion of basic to class type
Value of a is 30.5
In second method as mentioned above, type conversion of float type to class type is
performed. Same method can be used to overload other basic data types as int, double
etc.
2. Conversion from class type to basic type
In this type of conversion, on right side of = sign is a class type and on left side
is basic data type. This is not as simple as previous conversion was. In this
type of conversion, compiler does not perform any conversion implicitly but
user is involved to explicitly tell the compiler how to perform conversion from
class to basic type.
Some important points about casting from class to basic type:
▪ It cannot be performed with constructor.
▪ The keyword operator is mandatory to use which will be followed by basic type (int,
float, double etc.).
▪ Another name of such conversions is- overloading of type cast operators.
Following simple program makes it clear that how typecasting of class type to basic
type occurs.

//C++ code to perform typecasting of class type to basic type


#include <iostream>
using namespace std;
class A
{
int x;
public:
operator int ()
{
x = 90; It indicates conversion of class to int data
return (x); type
}
};
int main ()
{
int y = 3;
cout<<"Value before conversion "<<y;
A o1; //o1 is object of class A
y = int (o1); //typecasting of class A into int
cout<<"\nValue after conversion "<<y;
return 0;
}
Output
Value before conversion 3
Value after conversion 90
Explanation of above example:
In above code, when compiler reached at main function then int y with value 3 is
printed. After this, as object named o1 is created for class ‘A’ and its cast is converted
into integer y. Now, this line will call operator int () function code of class A. Make sure
if cast of o1 is firstly converted into int and then passed to y in main (), same will be
matching with basic type mentioned with operator keyword in class body.
From output, it is clear that y was having value 3 before any conversion of class data
type in it but when conversion of class type is performed in y then its value became 90
which came from class type.
3. Conversion from class type to another class type
▪ It is a type of conversion between objects of different classes.
▪ It means both source type and the destination type is of class type i.e. the source
type is of class type and the destination type is also of the class type.
▪ In other words, one class data type is converted into the another class type.
Consider a program having two classes.
One is class A and other is class B.
If A is destination and B is source then conversion of something from B to A is type
conversion of class to class type.
Such conversion can be expressed as:
Object_A = Object_B
It means, object of B is converted into type A and then assigned to object_A.
Again, two methods are useful to perform it:
1. Use of one parameter constructor
2. Use conversion function.
In simple words, let “computer” is one class (source class) and “mobile” is another
class (destination class).
Now, let “rate” is one data item of “computer” class.
If we want to assign “rate” to “mobile class” from “computer” class then: use class to
class type conversion as:
mob = comp ; // mob and comp are objects
Basically “comp” object is converted into “mob” object because comp is base class with
“rate” data item.
Following example is using one parameter constructor for performing conversion of
one class type to another.
// Example to express type conversion of one class to another class
#include <iostream.h>
#include <conio.h>
class mobile //destination class for conversion
{
int x;
public:
mobile (int x1)
{
x = x1;
}
void show ( )
{
cout<<”Value in destination class”<<x;
}
};
class computer //source class for conversion
{
int y;
public:
computer ( int y1)
{
y= y1;
}
operator mobile ( )
{
int aa;
aa= y * 2; //”y” data item is of source class “computer”
return mobile (aa);
}
};
void main()
{
clrscr();
computer o2 (10); //computer is source class
mobile o1; //mobile is destination class
o1 = o2; // pass object of source class “computer” to “mobile” class
o1.show ();
getch();
}
Output
Value in destination class 20

Explanation of above example:


In it, computer is source class and mobile is destination class.
Type conversion is done in source class by using syntax:
operator destination_classname ( )
{
--- //here data item of source is accessed by destination class.
}
In main function, object o2 of source class is passed to object o1 which is of
destination class.
Statement o1.show () will print output 20 which is execution of statement:
aa= y * 2.
Value of y is captured from source class “computer”.

◆◆◆◆◆
Chapter 6
Inheritance
7.1 INTRODUCTION

▪ Inheritance is a technique of code reuse which is an important feature called


reusability.
▪ Inheritance in Object Oriented Programming is a process of creating new classes
from existing classes.
▪ When creating a class, instead of writing completely new data members and
member functions, the programmer can assign that the new class should inherit
the members of an existing class. This existing class is called the base class, and
the new class is referred to as the derived class.
▪ In other terms, base class represents parent class and derived class represents
child class.
▪ Here, derive class/classes inherit some of the properties and behaviour of the
existing classes.
▪ In general life, inherit means derive characteristics from parents or ancestors.

Example: "She had inherited the fair complexion from her mother".

7.2 CONCEPT OF DERIVATION AND DEFINING DERIVED CLASS


A class can be derived from more than one class, which means it can inherit data and
functions from many base classes at same time in same program.
To describe a derived class, we use a class derivation list to specify the base class (es).
A class derivation list names one or more base classes and has the form −
class derived-class : access-specifier base-class
Where access-specifier is one of public, protected, or private, and base-class is the
name of a previously defined class.
If the access-specifier is not used, then it is private by default.
S. Derivation Type of base class members during
No Type by inheritance
derive
class

public protected
private
1 public public protecte not
d acces
sible
2 protected protecte protecte not
d d acces
sible
3 private private private not
acces
sible

7.3 FORMS OF INHERITANCE


Inheritance exists in five forms.
1. Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance

1. Single Inheritance
One base class and one derive class.

D
Single Inheritance

2. Multilevel Inheritance B

Inheritance is at many levels.


D1
At each level- new derived class is generated for
which previous level derived class become its base.
D2

D3
Multilevel Inheritance
In above diagram, inheritance is at many levels.
At level 1- D1 is derive of base B.
At level 2- D2 is derive of base D1.
At level 3- D is derive of base D2.

3. Multiple Inheritance
Many base classes of one derive class.
Multiple base classes at same level forms multiple inheritance

B1 B2 B3

D
Multiple Inheritance

Here, B1, B2 and B3 are three base classes of one derive class D.
4. Hierarchical Inheritance
It is tree shaped inheritance with more derive classes from one base class.

D1 D2 D3

Hierarchical Inheritance

5. Hybrid Inheritance:
It is combination of more than one type of inheritance. Combination is preferred from
above mentioned inheritance types.
Hierarchical Inheritance + Multiple Inheritance = Hybrid Inheritance
Multiple Inheritance + Multilevel Inheritance = Hybrid Inheritance
Hierarchical Inheritance + Multilevel Inheritance = Hybrid Inheritance

B1 B2

Hybrid Inheritance

7.4 AMBIGUITY IN INHERITANCE

Ambiguity occurs in multiple inheritance and an inheritance which occurs in


multipath.
In multiple inheritance, if two base classes (let class A and class B) have same named
function (let void show ()) then ambiguity occurs if these A and B classes will be
inherited in a common derive class (let C).
Example mentioned below tells about error message generated by compiler when
ambiguity occurs.
//Example representing ambiguity in multiple inheritance
#include <iostream>
using namespace std;
class A {
public:
void show()
{ cout << "A" << endl; }
};
class B {
public:
void show()
{ cout << "B" << endl; }
};
class C : public A, public B //Two copies of show () exists in class C
{ };
int main()
{
C obj;
obj. show();
return 0;
}
Output Error
error: request for member 'show' is ambiguous
Another case of ambiguity in inheritance:
Multipath Inheritance: A derived class (let C) with two base classes (let D1 and D2)
and these two base classes have one common base class (let B) is called multipath
inheritance.
Ambiguity in C++ occurs when a derived class have two base classes and these two
base classes have one common base class. Consider the following figure:

B
D1 D2

C
Figure showing ambiguity in class ‘C’
Here, C is derived from two classes D1 and D2 directly. Classes D1 and D2 both have
common base class (B class).
It means there are two paths via which data of B class reaches to C and the data is
same (called ambiguous data or duplicate data).
If inheritance is via multipath (more than one path) then one base class will be
inherited by different derive classes. So it means, derive classes will have common
copy of base (copy of B class). If these derive classes (D1, D2) have further one derive
class (same as multiple inheritance) then duplicate copy of root base class (which was
common) will be generated.
Following figure elaborates same concept in more detail.

Figure: Ambiguity in Multiple and Multipath Inheritance

In the above figure, both ClassD1 & ClassD2 inherit ClassB; they both have single


copy of ClassB.
However ClassC inherit both ClassD1 & ClassD2, therefore ClassC have two copies
of ClassB, one from ClassD1 and another from ClassD2.
If we need to access the data member of ClassB through the object of ClassC, we must
specify the path from which data of B will be accessed, whether it is
from ClassD1 or ClassD2, because compiler can't differentiate between two copies
of ClassB in ClassC.
The code written in following example
It tells about ambiguity in inheritance.
// Example of C++ ambiguity in multipath inheritance
#include <iostream>
using namespace std;
class B
{int a;
public:
void get ()
{ a = 50; }
};
class D1 : public B
{ };
class D2 : public B
{ };
class C : public D1, public D2
{ };
int main()
{ C ob;
ob. get ( ); //Error occurs
return 0;
}
Output Error message: Compilation failed due to following error(s).
request for member 'get' is ambiguous

ob.get (); //Error occur


As same copy of get () function is available in D1 and D2. Class C has duplicate copies
of get () function.
During execution, when object ob for C class is created to call get () function then
output of get () will not be printed because of ambiguity and compiler is unable to
decide which get () to pick. Such problem should be avoided.

7.5 METHODS FOR AVOIDING AMBIGUITY


There are basically two familiar methods as mentioned below:
▪ Using scope resolution operator
▪ Using virtual base class
Method 1:  Avoid ambiguity using scope resolution operator (: : )
Using scope resolution operator (: : ), manually specify the path from which data
member will be accessed. It is useful in class C as it is accessing D1 and D2 where
both D1 and D2 have one common base class B.
If “a” is data member of Class B, then- avoid ambiguity which arises due to data “a” as
mentioned below:
D1 :: a = 10; // means a is member of class D1
D2 :: a = 20; // means a is member of class D2
Following examples makes the concept easy to understand:
//Example using scope resolution operator to remove ambiguity in multiple inheritance
#include <iostream>
using namespace std;
class A {
public:
void show()
{ cout << "A" << endl; }
};
class B {
public:
void show()
{ cout << "B" << endl; }
};
class C: public A, public B
{ };
int main()
{ C obj;
obj. A :: show(); //show ( ) of class A
obj. B :: show(); //show ( ) of class B
return 0;
}
Output:
A

B
In above example, output of two classes inherited in one common class with same
named fuction is printed without any error.
Following statements:
obj. A :: show() and
obj. B :: show() have removed ambiguity.
Another example to remove ambiguity in multipath inheritance:
//Example using scope resolution operator to remove ambiguity.
#include <iostream>
using namespace std;
class B
{ public: void get ( )
int a =100;
};
class D1 : public B
{ };
class D2 : public B
{ };
class C : public D1, public D2
{ };
int main()
{
C ob;
cout<< "\n A : "<< ob.D1 :: a; //no ambiguous value
return 0;
}
Output: A 100
According to above example, class C has two copies of “a” with same value 100. It is
ambiguity.
Here, during call of such members, scope resolution operator has removed ambiguous
problem.
Another example to remove ambiguity in multipath inheritance:
// Example using scope resolution operator to remove ambiguity.
#include <iostream>
using namespace std;
class B
{ int a;
public:
void get ()
{ a = 50;
cout<<"Value is "<<a;
}
};
class D1 : public B
{ //here get () function copy is inherited
};
class D2 : public B
{ //here get () function copy is inherited
};
class C : public D1, public D2
{ //here two get () copies are inherited
};
int main()
{ C ob;
ob. D1 :: get ( ); // It means get () of D1 should be called
return 0;
}
Output

Value is 50

Method 2. Avoid ambiguity using virtual base class


As for class C, multiple copies of class B exists. To remove these multiple copies,
inherit class B as virtual class in both D1 and D2 classes.
Figure below showing class B as virtual base class.

B is now virtual base class


B

D1 D2

C
Figure: Virtual base class concept
The code in following examples has removed ambiguity by making base class as
virtual class.
// Example using virtual base class concept to remove C++ ambiguity
#include <iostream>
using namespace std;
class B
{ public:
int a =100;
};
class D1 : virtual public B
{ };
class D2 : virtual public B
{ };
class C : public D1, public D2
{ };
int main()
{
C ob;
cout<< "\n A : "<< ob.a;
return 0;
}
Output:

A 100
In above example, class D1 has a copy of “a” with value 100.
Class D2 also has a copy of “a” with value 100.
Now, class C has two copies of “a” with same value 100.
By making base class B as virtual, this ambiguity has been easily removed and so, in
output only one copy of “a” is printed.
Another example using virtual base class concept:
// Example using virtual base class concept to remove C++ ambiguity.

#include <iostream>

using namespace std;


class B

{ public: int a; };

class D1 : virtual public B { };

class D2 : virtual public B { };

class C : public D1, public D2 { };

int main()

C ob;

ob.a = 10; // No error ………….. (1)

ob.a = 50; // No error ……………..(2)

cout<< "\n A : "<< ob.a;

return 0;

Output :
A : 50

In this example, C has only one copy of B therefore statement (2) will overwrite the
value of a, given at statement (1). So, value 50 is printed.

7.6 OBJECT SLICING


During inheritance, when object of derived class is copied to an object of base class
then object slicing occurs. But in this process, base class (super class) slices off the
information of derived class (sub class).
Let B is name of base class and D is name of derived class.
Then B = D is basic concept of object slicing.
It uses assignment operator.
It is basically upcasting in inheritance.
For explaining the problem of object slicing, must pass object of derived class to base
class.
//Example showing concept of oblect slicing in programming
Class B
{
protected : int x;
};
Class D : public B
{
protected : int y;
};
void main ( )
{
B o1;
D o2;
o1 = o2 ; //upcasting as passing derived class object to base class
}
After executing above concept, the information about member y from object o2 is lost
in o1 (object of base).
As slicing means pieces and here also, after passing object of D to B, slices of D are
lost but B class maintains only information of its own class.
This is basically a problem in programming which occurs during upcasting.

7.7 OVERRIDING MEMBER FUNCTIONS

It is also called Function Overriding.


It occurs in inheritance, not in one class because overriding belongs to different
objects.
The overloaded function signature should be same (signature means- return type and
arguments of function). So, concept of base and derived class is useful.
The name of function in base and derived class should be same as shown in example
below:
//Same named function in base and derive class
class B
{
public:
void show( )
{ cout << "Base class"; }
};
class D : public B
{
public:
void show( )
{ cout << "Derive Class"; }

};

Function Overriding: Function overriding is a feature of OOPs Programming that


allows us to ignore a function of parent class in child class. Basically, Overriding is
needed when derived class function has to do some additional or different job than the
base class function. If we create an object of the derived class and call the member
function which exists in both classes (base and derived), the member function of the
derived class is invoked and the member function of the base class is ignored. This
feature in C++ is known as function overriding. It means, there occurs overriding of
base class function by derived class function.
Following code in C++ helps to understand how overriding of function occurs.
//Example expressing calling of overridden function
class B
{
public:
void show()
{ cout << "Base class"; }
};
class D : public B
{
public:
void show()
{ cout << "Derive Class"; }
};
int main()
{
D d; //Derive class object
d.show();
}
Output:
Derive class
In above example, the derived class function overrides the base class function. So,
output of show () of derived is shown on output screen.
The scope resolution (:: ) operator can be used to access base class function through
an object of the derived class.
For example:
D ob;
Ob. B :: show (); //show () is of B class
Another type of Function Overriding (at run time)
It uses the concept of pointer object of base class and it is linked with Run time
polymorphism. It is covered in chapter 8th under virtual function.

7.8 OBJECT COMPOSITION AND DELEGATION


Composition is used in terms of object modelling as a "has-a" relationship and is a
form of association (another being aggregation). This is usually different than
“inheritance" ("is-a" relationship). 
For example, a House has a set of Rooms. That's a composition relationship. 
Delegation is nothing more than an implementation detail. It refers to one object being
dependent on another object to provide functionalities. 
Delegation is closely related to object composition i.e. when object of one class acts as
a data member in another class.
Difference between Composition and delegation:
Composition implies that the child cannot exist without the context of the parent.
For instance, a school has one or more classes.
That's a composition relationship.
If we remove the school from existence, the classes stop to exist.
A school also has a number of students, being instances of Person.
That's a delegation because those students exist outside of the framework of that
school too.

7.9 ORDER OF EXECUTION OF CONSTRUCTOR AND DESTRUCTOR

As we know, default constructor of a class is invoked automatically when an object of


a class is created. So, it initializes the members of the class.

Figure: Order of Inheritance


In inheritance as shown in above figure, the order of constructors calls (of base class
and of derive class) is as shown and explained below:

Figure: Order of Constructor Call in Inheritance


If object of derived class is created then:
The base class’s default constructors will be invoked first and then the derived class’s
default constructor will be invoked.
Reason: As it is clear that during inheritance, if a class B is inherited in another class
D using following statement:
Class D: public class B
Then:
Automatically data members and member functions of base class come in derive class
based on access specifier used.
When object of class D is created in main ( ) as:
D ob;
All of the members of derived class need to be initialized but the inherited members in
derived class can only be initialized by the base class’s constructor as the definition of
these members exists in base class only. This is why the constructor of base class is
called first to initialize all the inherited members.
// Example showing order of execution of Constructors
include <iostream>
using namespace std;
class B
{
    public:
     B ()
    { cout << "Inside base class" << endl;     }
};
 class D : public B
{
    public:
         D ( )
    {        cout << "Inside sub class" << endl;     }
};
 int main( ) // main function
{
D ob; // ob is object of derived class
return 0;

}
Output
Inside base class
Inside sub class
Order of constructor call in Multiple Inheritance
As in multiple inheritance, bases classes are more than one. So,
The base class’s constructors are called in their order of inheritance and then the
derived class’s constructor is called.
//Example expressing order of constructors call in Multiple Inheritance:
#include <iostream>
using namespace std;
 // first base class
class B1
{       
    public:
         // first base class's Constructor   
    B1()
    {        cout << "Inside first base class" << endl;    }
};
 // second base class
class B2
{
    public:
     // second base class's Constructor
    B2()
    {        cout << "Inside second base class" << endl;     }
};
 // C class inherits B1 and B2
class C : public B1, public B2
{
    public:
     // child class's Constructor
C ()
    {        cout << "Inside child class" << endl;     }
};
 // main function
int main()
{          // creating object of class Child
C ob;
return 0;
}
Output
Inside first base class
Inside second base class

Inside child class


It is important to note that the parameterised constructor of base class cannot be
called in default constructor of derived class; it should be called in the parameterised
constructor of derived class.
Order of destructor call in Inheritance
Destructors in C++ are called in the opposite order of that of Constructors.
As we know, members are destroyed after destructor is called which is also of same
name as class name but with tilde sign preceding it.
So, it free up the resources.
Destructor always runs in opposite order as constructors runs as shown in following
diagram.

Figure: Order of Destructor call in Inheritance


If in a program, inheritance occurs and both base and derived class have constructors
and destructors then:
The order is:
Base constructor
Derived constructor
Derived destructor
Base destructor

//Example illustrating calling of base and derive constructor destructor.


#include <iostream>
using namespace std;
class B
{
public:
B()
{ cout<<"Construct B"<<endl; }
~B()
{ cout<<"Destruct B"<<endl; }
};
class D : public B
{
public:
D()
{ cout<<"Construct D"<<endl; }
~D()
{ cout<<"Destruct D"<<endl; }
};
int main()
{
D ob;
return 0;
}
Output:
Construct B
Construct D
Destruct D
Destruct B

◆◆◆◆◆
Chapter 7
Pointers and Dynamic Memory
Management
4.1 INTRODUCTION
During programming, when a user initializes a variable (let: int a=2 ;), then
automatically a free memory address is assigned to the variable.
So the result is: variable “a” with value 2 is stored at that memory address.
In this scenario, we don’t need to worry about what specific memory address is
assigned. All is performed by compiler. But it is without pointers. Such space is
allocated in static way.
On other side, pointers have supported memory management dynamically which
means no memory space wastage.

Definition of Pointers

A pointer is a variable that holds a memory address as its value.


We can say a pointer is a variable which stores address of another variable.
Pointer uses two operators.
▪ The address-of operator (&) (also called reference operator)
▪ The dereference operator (*)
Like any variable or constant, must declare a pointer before you can work with it.
Some C++ tasks such as dynamic memory allocation cannot be performed without
pointers.

4.2 DECLARING, INITIALIZING AND ACCESSING THROUGH POINTERS


Syntax for pointer declaration:
type * pointer_variable_name;
Examples using pointer:
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
As we know, each variable in memory has a memory location. This memory location
can be accessed using ampersand (&) operator which denotes an address in memory.
Always address is assigned to a pointer type variable.
It is a kind of indirect reference to access data.
Let x is a variable and p is a pointer variable pointing to x then it can be created as
written below:
int x = 20, *p; // x assigned integer value 20, p declared as pointer
p = &x; // pass address of x to pointer p
cout<<p; //output: Address of x
cout<<*p // output=20 (same as x has value but through its address)

4.3 POINTERS ARITHMETIC


Basically there are four arithmetic operators that can be used on pointers: ++, --, +,
and -.
Let a variable named “ptr” is an integer pointer which points to the address 1000.
Assuming 32-bit integers, let us perform the following arithmetic operation on the
pointer:
Operation:
Post Unary increment:
Use it as:
ptr ++
Now ptr will point to the location 1004 because each time ptr is incremented, it will
point to the next integer. This operation will move the pointer to next memory location
without impacting actual value at the memory location.
If ptr points to a character whose address is 1000, then above operation will point to
the location 1001 because next character will be available at 1001.

4.4 MEMORY MANAGEMENT THROUGH POINTERS: NEW & DELETE


The keywords new and delete are C++ memory management operators.
These are also called dynamic memory allocation/deallocation operators.
It uses Heap data structure.
It is combination of two separate operators: new, delete
Declaring a pointer:
These are declared same like normal variables but must use * before variable name.
Like:int *p;
// a pointer named p to an integer value that is pointer to an integer variable
float *p1;
// a pointer named p1 to a float value that is pointer to a float variable
double *p2;
// a pointer named p2 to a double value that is pointer to a double variable
int *p3 , *p4;
// declare two pointers named p3 and p4 to integer variables
char *p; // pointer to character
In following statement:
int p5, *p6;
p5 variable is declared as non pointer variable but p6 is declared as pointer variable.
So, p5 can hold value of any variable but p6 will hold memory address of another
variable that will be initialized to it.
It means p6 = & p5 is correct.
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
If statement is:
int * getp ( ) ;
then it means:
getp is a function which is returning a value of type int* and not an int.
Following example uses concept of pointers in C++ program
#include <iostream>
using namespace std;
int main()
{
int x = 5;
cout << x << '\n'; // print the value of variable x
cout <<&x << '\n'; // print the memory address of variable x
cout << *&x << '\n'; /// print the value at the memory address of variable x
return 0;
}
Output:
5                                                                                                                             
0x7ffd04b7f47c

4.5 INITIALIZING POINTERS (ASSIGNING A VALUE TO A POINTER)
For this purpose: Use the address-of operator since pointers only hold addresses.
Value assigned to a pointer must be an address.
One of the most common things to do with pointers is:
Pointers hold the address of a different variable.
Let:
int a = 4;
int *p = &a; // initialize p with address of variable named ‘a’
// Memory address: 0012FF7B (value of p variable – pointer)
It means pointer is a concept of ”pointing to” a value.
// Example using concept of pointers and reference operator:
#include <iostream>
using namespace std;
int main()
{
int a = 5;
int *p = &a; // initialize pointer p with address of variable a

cout <<&a << endl ; // print the address of variable value


cout << p ; // print the address that p is holding
return 0;
}
Output:
0x7ffd04b7f47c
0x7ffd04b7f47c
//Another example to illustrate correct and incorrect use of pointers and reference
operator:
#include <iostream.h>
void main()
{
int a = 5 , *p1;
float b=2.9, *p2;
p1 = &a; // correct
p2 = &b; // correct

p1 = &b;
// incorrect since int pointer cannot point to the address of a double variable
 p2=&a;
// incorrect since float pointer cannot point to the address of an int variable
getch( );
}

Output:
Compilation failed due to following error(s).
p1 = &b;
cannot convert 'int*' to 'float*' in assignment
p2=&a;
4.6 ACCESSING DATA THROUGH POINTERS
Use Dereferencing pointers for this purpose.
It helps to retrieve the data of the address a pointer variable is pointing to.
Another example using pointers:
#include <iostream>
using namespace std;
int main()
{
int a = 5;
cout<<&a<<endl; // prints address of value (0012FF7C)
cout<<a<<endl; // prints contents of value (5)
int *p;
p = &a;
// initialize pointer p with address of variable a means p “points to” a
cout << p << endl ;
// prints address held in p, which is same as &a (0012FF7C)
cout << *p ; // dereference p (get the value that p is pointing to- (5))
return 0;
}
Output
0x7ffd717c28ec
5
0x7ffd717c28ec
5

4.7 THIS POINTER


In C++, each object can have access to its own address through this pointer.
This is a special kind of pointer.
This pointer is a pointer accessible only within the nonstatic member functions of
a class, struct or union type.
It points to the object for which the member function is called.
Static member functions do not have this pointer.
This pointer is a hidden pointer inside every class member function that points to the
class object.
It can be used in following two ways:
this
this->member-identifier
An object's this pointer is not a part of the object itself; it is not reflected in the result
of a sizeof statement on the object. Instead, when a nonstatic member function is
called for an object, the address of the object is passed by the compiler as a hidden
argument to the function.
For example, the following functions call:
The object's address is available from within the member function as this pointer.
Most uses of this are implicit. It is legal, though unnecessary, to explicitly
use this when referring to members of the class.
For example:
void Date:: setMonth( int mn )
{
month = mn; // These three statements
this->month = mn; // are equivalent
(*this).month = mn;
}
The expression *this is commonly used to return the current object from a member
function:
return *this;
This pointer is also used to guard against self-reference:
if (&Object != this) {
// do not execute in cases of self-reference
Because this pointer is not modifiable, assignments to this are not allowed. Earlier
implementations of C++ allowed assignments to this

Occasionally, this pointer is used directly — for example, to manipulate self-referential


data structures, where the address of the current object is required.

4.8. DIFFERENCE BETWEEN STATIC MEMORY ALLOCATION & DYNAMIC


MEMORY ALLOCATION

S. Static Allocation Dynamic Allocation


N
o
1 It is performed at static time It is performed at dynamic
means during compile time. time means at run time.
2 It is assigned to stack It is assigned to heap

3 It follows FIFO structure There is no specific order of


(First-In-First-Out) assignment.
4 Size must be known is Size may be not known at
advance i.e. at compile time. compile time.
5 Prefer to use it if required It is best to use if we don’t
memory size is known in have idea about how much
advance. memory required.
4.9 C LANGUAGE DYNAMIC MEMORY ALLOCATION
In C program:
Following C standard library functions are used to allocate memory dynamically. It means
that memory is allocated during runtime.
▪ malloc()
▪ calloc()
▪ free() and
▪ realloc()

C malloc ()
It allocated the memory space of given size. Also it returns the pointer to beginning of
the block.
It doesn’t initialize the allocated memory.

C calloc()
The name calloc stands for "contiguous allocation".
The only difference between malloc() and calloc() is that:
malloc() allocates single block of memory whereas calloc() allocates multiple blocks of
memory each of same size and sets all bytes to zero.
Syntax of calloc()
ptr = (cast-type*)calloc(n, element-size);
This statement will allocate contiguous space in memory for an array of n elements.
For example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each
of size of float, i.e, 4 bytes.

C free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed
on its own. You must explicitly use free() to release the space.
syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.

Example 1: Using C malloc() and free()


//Write a C program to find sum of n elements entered by user. To perform this
program, allocate memory dynamically using malloc() function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}

Example 2: Using C calloc() and free()


//Write a C program to find sum of n elements entered by user. To perform this
program, allocate memory dynamically using calloc() function.
#include <stdio.h>
#include <stdlib.h>
int main()
{ int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) calloc(num, sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}

C realloc()
If the previously allocated memory is insufficient or more than required, you can
change the previously allocated memory size using realloc().
Syntax of realloc()
ptr = realloc(ptr, newsize);
Here, ptr is reallocated with size of newsize.

4.10 PROBLEMS RELATED TO POINTERS

No doubt, pointers are flexible. Also memory management through pointers use is
more beneficial than static allocation. Yet following are some problems which arise
with the use of pointers.
1. Null pointer
2. Memory Leak
3. Memory Corruption
4. Dangling Pointer
5. Wild Pointer

1. Null Pointer: It is a kind of problem which arises when a pointer variable is declared in a
program but not any address is assigned to it.
Solution to this problem:
Either assign NULL to such pointer variable as:
int *p;
P = NULL;
Or
Erase such pointer variable which is not used later also.
When NULL is assigned to pointer variable then it gives output zero (0).

2. Memory Leak: This problem is also called FATAL-OUT-OF-MEMORY.


It is wastage of memory. That’s why counted as problem of pointers.
According to it, memory is allocated but it is not freed (deleted).
It is unsuccessful use of memory management operators new and delete.
In this scenario, new is used nut programmer forgot to use delete.

FATAL-OUT-OF-MEMORY FATAL-OUT-OF-MEMORY not


class A existing
{ class A
}; {
main () };
{ main ()
A *ob; {
ob = new A [3]; A *ob;
//memory wastage as ob = new A [3];
allocated memory is not deleted delete [ ] ob;
} //no memory wastage
}

3. Memory Corruption: This problem occurs because of different reasons like, if contents of
a memory location are accidentally changed.
Mostly memory corruption occurs because of programming errors. If in a program, data is
written to wrong memory location then also it becomes memory corruption. It means
going against memory safety.
Some other reasons of memory corruption are as following:
▪ Attempting to free memory already freed.
▪ Freeing memory that was not allocated.
▪ Attempting to read/write memory already freed.
▪ Attempting to read/write to memory which was never allocated.
▪ Memory allocation error.
▪ Reading/writing to memory out of the bounds of a dynamically allocated array

4. Dangling pointer: Sometimes there can be a problemlike, An object is destroyed but a


pointer pointing to such object was not destroyed. So, it is created unsatisfactory
behavior.
So, if a pointer is pointing to an invalid object (may be deleted object) then it is called
dangling or hanging pointer.
{
int * p = NULL; // p= 0 value assigned at run-time

{
int x;
p = & x; // Now p is a dangling pointer
}
5. Wild Pointer: It is also called uninitialized pointer as wild pointer points to illogical
memory locations. So, many times, wild pointer caused a program to behave badly.
These are called unbound pointers.
Case 1: Wild Pointer
int main()
{
  int  *p; //p is wild pointer
}

Case 2: Not Wild Pointer


int main()
{
  int  *p; //p is wild pointer
  int x=20;
  p = &x;  //Now p is not a wild pointer
}

4.11 POINTERS AND DYNAMIC MEMORY MANAGEMENT

A pointer is a data object which contains the address of some other data object So, if x
contains the address of y then programmers say: "x points to y."
Dynamic memory is allocated using operator new. New is an operator.
New operator:
New is followed by a data type specifier (int, float, chat etc) and if more than one
element is required, the number of these are mentioned within brackets [].
It returns a pointer to the beginning of the new block of memory allocated.
Its syntax is:
pointer = new type; ------------------------- Expression 1
Or
pointer = new type [ number-of-elements]; ------------------------- Expression 2

Expression 1 is used to allocate memory to contain one single element of type type.
Expression 2 is used to allocate a block (an array) of elements of type type, where
number-of-elementsis an integer value representing the amount of these. For example:
int * p;
p = new int [3];
In this case, the system dynamically allocates space for three elements of type int and
returns a pointer to the first element of the sequence,

p
Delete Operator:
Once the memory is allocated using new operator, it should be released back to the
operating system.
If the program uses a large amount of memory using new, system may crash because
there will be no memory available for the operating system.
The following expression returns memory back to the operating system.
delete [] ptr;
The brackets [] indicates the array has been deleted. If you need to delete a single
object then, you don't need to use brackets.
delete ptr;
So, to safely use pointers, releasing dynamic memory is also an important step. It is
possible with proper use of delete which is also an operator.
It is used after using completely new and before exiting from program as following:
int * p, p1;
p= new int [50];
p1= new int;
delete [ ] p;
delete p1;

//Example: Write a C++ program to store GPA of n number of students and display it
where n is the number of students entered by user. Use memory management operaots
for same.
#include <iostream>
using namespace std;
class Test
{
private:
int num;
float *ptr;
public:
Test()
{
cout << "Enter total number of students: ";
cin >> num;
ptr = new float[num];
cout<< "Enter GPA of students." << endl;
for (int i = 0; i < num; ++i)
{
cout << "Student" << i + 1 << ": ";
cin >> *(ptr + i);
}
}
~Test() {
delete[] ptr;
}
void Display()
{
cout<< "\nDisplaying GPA of students." << endl;
for (int i = 0; i < num; ++i) {
cout << "Student" << i+1 << " :" << *(ptr + i) << endl;
}
}

};
int main() {
Test ob;
ob.Display();
return 0;
}
Output
Enter total number of students: 4
Enter GPA of students.
Student1: 2.3
Student2: 3.8
Student3: 3.9
Student4: 2.7

Displaying GPA of students.


Student1: 2.3
Student2: 3.8
Student3: 3.9
Student4: 2.7

In above program example, when the object ob is created, the constructor is called
which allocates the memory for num floating-point data. When the object is destroyed,
i.e, when the object goes out of scope, destructor is automatically called.
~Test() {
delete[] ptr;
}
This destructor executes delete [ ] ptr; and returns memory back to the operating
system. This is dynamic memory management.

4.12 BENEFITS OF POINTERS

● Arrays are implemented using pointers. Pointers can be used as an alternative to


array indices.Pointers are the only way you can dynamically allocate memory in
C++ which is the most common use case for pointers.
● They can be used to pass a large amount of data to a function in a way that
doesn’t involve copying the data, which is inefficient.
● Pointers can be used to pass a function as a parameter to another function.
● Pointers can be used to achieve polymorphism when dealing with inheritance.
● Pointers can be used to have one struct/class point at another struct/class, to
form a chain. This is useful in some more advanced data structures, such as
linked lists and trees.

◆◆◆◆◆
Chapter 8
Virtual Functions &
Polymorphism
8.1 POLYMORPHISM
It is one of the important and strongest features of Object Oriented Programming
(OOP).
Basically polymorphism means poly + morph = one name in many forms.
Morph is one thing and Poly means many forms.
Types of Polymorphism:
It has two types.
▪ Compile time Polymorphism
▪ Run time Polymorphism
Compile time polymorphism is also called Early Binding or Static Binding.
On other side, run time Polymorphism is also named as Late Binding or Dynamic
Binding. Further types of Polymorphism are neatly structured in following diagram.

Polymorphism

Compile-Time Run-Time
(Early Binding) (Late Binding)

Function Overloading Operator Overloading Virtual Function

Figure: Types of Polymorphism


Following broad situation expresses the situation in which polymorphism occurs
(applicable for function overloading also).
1. If same named function is used for more than one time but :
Either
With different types of parameters
Or
With parameters different in length
It means if a function is ‘sum’ then:
(a) void sum (int, int)
(b) void sum (int, float)
(c) void sum (float, float)
(d) void sum (float, double)
(e) void sum (int, int, int)
(f) void sum (int, int, int, int)
(g) void sum (int, float, int, int)
(h) void sum (int, int, float, int)
and many more
It is clear from above forms of function ‘sum’ that:
It is possible to utilize one thing in many forms.
From (a) to (d)- function sum is having same number of parameters which are two but still is
under polymorphism as type of parameters are different.
So, values pass to these will be based on type of argument and its position. Arguments are
same as parameters which are passed in parenthesis of a function.
1. Sum (10, 20)
2. Sum (20, 27.7)
3. Sum (4.5, 5.6)
4. Sum (6.7, 4000000)
5. Sum (1, 2, 3)
6. Sum (100, 200, 300, 400)
7. Sum (100, 16.9, 300, 400)
8. Sum (100, 300, 16.9, 400)
Values can by any in the range of its type of variable. 1 is for (a), 2 is for (b) and 8 is for (h).
As already mentioned:
Polymorphism is possible at compile time and also at run time.
The compile time polymorphism related the objects at or during compilation process but in
run time polymorphism, the class objects are related during execution.
1.1 FUNCTION OVERLOADING
If a class has multiple functions with same names but with different parameters
(arguments passed) then they are said to be overloaded.
Function overloading allows user to use same name for different functions so that
several functions can be performed in same class.
It is usually used to enhance the readability of the program.
If user has to perform one single operation but with different number of arguments or
types of arguments, then you can simply overload the function.
Listed below are two methods to overload a function:
1. By having different number of Arguments.
2. By having different types of argument.
There is one more important method which is supportive for performing overloading a
function:
This method is “By changing sequence of arguments”.

Method 1: By having different number of Arguments


As arguments are parameters passed to a function.
Different number of arguments means:
One function has one argument, second has two, and third has three and so on. In
this case, all arguments can be of same or different type.
Let function name is : show ( ), it can be overloaded as per method 1:
show (int);
show (int, int);
show (int, int, int)
……..
In following example, function sum() is overloaded and used two times.
It is adding two integer numbers and again in another form- it is adding three integer
numbers.
//Example to show Function Overloading by different number of
arguments
#include <iostream>
using namespace std;
class load //load is name of class
{
public:
int sum (int x, int y) //sum () adding two nos
{
cout << x+y<<endl;
}
int sum (int x, int y, int z) //sum () adding two nos
{
cout << x+y+z;
}
};
int main ()
{
load ob;
cout<<"Sum of numbers by Function overloading method 1 :\n";
ob.sum (10,20); // sum() with 2 parameter will be called
ob.sum(10,20,30); //sum() with 3 parameter will be called
return 0;
}
Output
Sum of numbers by Function overloading method 1 :
30
60
Method 2: By having different types of argument
This type of function overloading can be implemented by same name of function, same
number of parameters and used more than one time, but the type of parameter is
different. 
Let’s take in an easy way- a function name is: get ( ), it can be overloaded as per method 2:
get (int);
get (float);
get (double);
get (char);
……..
Take an example:
Let: sum () is a function used two times. Each time: name is sum ( ) and numbers of
parameters are same (2 parameters). But, in each new form, type of parameter is
different.
Like:
sum (int, int);
sum (double, double);
….
//Example to show Function Overloading by different type of arguments
#include <iostream>
using namespace std;
class load //load is name of class
{
public:
int sum (int a, int b)
{
cout << a+b<<endl;
}
int sum(double c, double d )
{
cout << c+d;
}
};
int main ()
{
load ob;
cout<<"Sum of numbers by Function overloading method 2 :\n";
ob.sum (10,20); // sum() with 2 int parameter will be called

ob.sum(1.5, 2.2); //sum() with 2 float parameters will be called


return 0;
}
Output:
Sum of numbers by Function overloading method 2 :
30
3.7
Method 3: By changing sequence of arguments
According to this method, it is possible to overload a function in following way:
Let name of function is sum ( ) and it is used in two following two forms.
sum (int, float)
sum (float, int)
It means sum function is overloaded. As in both above mentioned forms, sequence of
arguments is different.
Following code makes the concept clear about overloading by having different sequence of
arguments.
//Example to show Function Overloading by different sequence of arguments
#include <iostream>
using namespace std;
class load //load is name of class
{
public:
int sum (int a, double b)
{
cout << a+b<<endl;
}
int sum(double c, int d )
{
cout << c+d;
}
};
int main ()
{
load ob;
cout<<"Sum of numbers by Function overloading method 3 :\n";
ob.sum (2, 3.5); // sum() with 2 int parameter will be called

ob.sum(5.5, 3); //sum() with 2 float parameters will be called


return 0;
}
Output:
Sum of numbers by Function overloading method 3 :
5.5
8.5
Now, following example explains about function overloading by adding all above mentioned
three methods in one program.
// Function Overloading example compiling all above three methods:
#include <iostream>
using namespace std;
class CalculateArea
{
public:
void Area(int r) //Overloaded Function 1
{ cout<<"\n\tArea of Circle is : "<<3.14*r*r; }

void Area(int l,int b) //Overloaded Function 2


{ cout<<"\n\tArea of Rectangle is : "<<l*b; }

void Area(double l,int b) //Overloaded Function 3


{ cout<<"\n\tArea of Rectangle is : "<<l*b; }
void Area(int l,double b) //Overloaded Function 4
{ cout<<"\n\tArea of Rectangle is : "<<l*b; }
};
int main()
{
CalculateArea C;
C.Area(5); //Statement 1
C.Area(5,3); //Statement 2
C.Area(7, 2.1); //Statement 3
C.Area(4.7,2); //Statement 4
return 0;
}
Output :
Area of Circle is : 78.5
Area of Rectangle is : 15
Area of Rectangle is : 14.7
Area of Rectangle is : 9.4
Explanation of program:
In above example: CalculateArea is class name defined by user.
In main () function, C is object name and then C is calling Area () function of
CalculateArea class as mentioned in statement 1 to 4. It is overloading of one function
as name of function in each call is same which is Area () but in each call, it is
performing differently.

1.2 OPERATOR OVERLOADING

It is also a feature of C++ language.


With this feature: an operator can be overloaded by performing special operation on it.
Such specialism allows the use of operator on OBJECTS.
Although an operator let plus (+) operator can be used in following many forms:
▪ For addition of two integers
▪ For addition of two strings
▪ For addition of two doubles
And many more.
Still, + can be overloaded if it will add two objects of a class.
Following examples shows the use of plus operator in different forms for above
mentioned three forms:
▪ For addition of two integers (for example- let two integers values 10, 20 - So
(10+20))
▪ For addition of two strings (for example- let two strings Jasrat , Chahal - So
(JasratChahal))
▪ For addition of two double values (for example- let two double values 10.9, 20.8 -
So (10.9+20.8))
But with operator overloading, it is possible to use same plus (+) operator for adding
two objects which is operator overloading in C++.
Let ob1, ob2 are two objects created for a class.
Then: ob1+ ob2 is operator overloading.
Even all other operators can also be overloaded same as binary plus.
In case Unary minus operator (--) to be overloaded then:
ob1-- or
--ob1 can be its two possibilities.
As per programming point, unary plus (++) operator can be overloaded as shown in
example below:
//C++ program for overloading unary pre increment (++) operator
#include<iostream>
using namespace std;
class overl
{ private: int a;
public:
void get ( )
{ cout<< "enter number ";
cin >> a; }
void operator ++ () //unary ++ operator overloading
{ ++ a ; //pre increment
}
void show ( )
{ cout << " value of a is: " << a; }
}; // class closes here
int main()
{overl o1;
o1. get ( ) ;
++o1 ;
cout << " after pre increment - >";
o1. show ( );
return 0;
}
Output:
enter number 10
after pre increment - > value of a is: 11
In chapter sixth, operator overloading is already covered in detail.
8.2 BINDING IN C++
In C++, binding occurs either at compile time or at run time.
If binding occurs at compile time then known as Early binding or Static binding. Also
called compile time Polymorphism.
If binding occurs after compilation i.e. at run time then known as Late binding or
Dynamic binding. Also called run time Polymorphism.
Difference between Early Binding and Late Binding:

S Early Binding Late Binding


.
N
o
Early binding also called  Late binding also called
Compile Runtime
1
polymorphism(Static polymorphism(dynamic
polymorphism)  polymorphism)
In it, object type is obtained In it, object type is obtained at
2 at compile time so it is run time so it is binding later.
binding earlier.
Compiler knows about Compiler does not know about
3 methods or properties of methods or properties of
objects objects until run time.
It does not use virtual It uses virtual keyword.
4
keyword.
It  is achieved by using It is achieved by using Virtual
5 Operator Overloading and function.
Function Overloading 
Compiler guarantees that The biggest advantages of Late
the function takes the exact binding is that the Objects of
number of arguments and this type can hold references
6 that they are of the right to any object.
type. Also checks that the
return value is of the correct
type.
Details about Early Binding and Late Binding in C++:
Early Binding in C++
In early binding, the compiler matches the function call with the correct function
definition at compile time. It is also known as Static Binding or Compile-time Binding.
By default, the compiler goes to the function body which has been called during
compile time. So, output of that class function prints for which pointer object is
created. This concept has only one difference with function overriding, rest is same.
Overriding of function when name of function is same does not use pointer of base
class concept but early binding uses this concept.
The code written in following example is using the concept of early binding.
Inheritance concept is important here.
It is mandatory to create pointer object of base class to allow binding.
As name of function in base and derive class is same. So, it allows polymorphism.
// Early Binding in C++ Program
#include <iostream>
using namespace std;
class Animals
{
public:
void sound()
{ cout << "This is parent class of Animals" << endl; }
};
class Dogs : public Animals
{
public:
void sound()
{ cout << "Dogs bark" << endl; }
};
int main()
{
Animals *a; //pointer of base class
Dogs d; // d is object of derive class “Dogs”
a= &d; // Derive class reference is passed to pointer object
a -> sound(); // early binding
return 0;
}
Output:
This is parent class of Animals
Explanation of above example:
This is due to Early Binding. As “a” is a pointer of the parent class referring to the
object of the child class. Since early binding takes place at compile-time, so when the
compiler saw that “a” is a pointer of the parent class, then it matched the call with the
‘sound ()' function of the parent class without considering to which object the pointer
is referring to.
Here, class “Dogs” has two copies of function “sound” but output of both is different.
Statement “a= &d” in main() function means, pass reference of derived class to pointer
object. When “a -> sound()” will be executed then rather than “Dogs bark”. The output
is of base class. It means, early binding concerns with the class for which pointer
object is created. It doesn’t matter whats contents are passed to pointer object.
This is the reason, due to which output of base class “Animals” is printed rather than
of “Dogs” class.
Another example of Early Binding:
// Overriding when virtual function concept is not used (Early Binding)
#include <iostream>
using namespace std;
class B
{
public:
void show ()
{ cout<< "base class \n"; }
};

class D: public B
{
public:
void show ()
{ cout<< "derived class "; }
};

int main ( )
{
B * p; //pointer object of base class

B ob1;
D ob2;

p = & ob1; // address of base class provided to pointer object


p -> show ();

p = & ob2; // address of derived class provided to pointer object


p -> show ();
return 0;
}
Output:
base class
base class

In above example: the question is why output of derived class is not printed when
reference of derived is passed to pointer object. The reason is: it doesn’t matter for
pointer object that which contents are passed to it but it matters that for which class
it is declared. So, base class output always overrides derived class output when
function name is same (requirement of polymorphism). So, the solution is: make
function virtual which is overriding another function. The concept of virtual function
can be implemented at Run-Time called Late Binding in C++.
Late Binding in C++
In the case of late binding, the compiler matches the function call with the correct
function body at runtime.
It is also known as Dynamic Binding or Runtime Binding.
In it, the compiler identifies the type of object at runtime and then matches the
function call with the correct function definition. So, it prints body of function whose
reference is passed to pointer object as virtual keyword means do not consider in
reality. As it is clear- by default early binding takes place. But if we declare base class
function as virtual then the problem of previous example (example of early binding)
can be solved.
8.3 VIRTUAL FUNCTION
▪ A virtual function is a member function of the base class which is overridden in
the derived class. The compiler performs late binding on this function.
▪ To make a function virtual, we write the keyword virtual before the function
definition.
▪ Virtual means not in reality but in effect. So, if a function is of type virtual then its
body usually does not print but it is defined as per concept of polymorphism.
▪ It is Run Time Polymorphism. So, Late Binding is allowed when concept of virtual
function is used in a program.
▪ It uses keyword virtual preceding the function to which programmer wants to make
of virtual effect. It means, a virtual function doesn’t exist in reality but it has an
effect in a program.
▪ It uses two basic concepts- one is pointer of base class which means object of base
class is created as pointer type and another is same named function in base and
derived class. Here, base class function is declared as virtual so that it will not
override the body of derived class function which is also of same name.
▪ It is also a member function declared within base class and is re-defined by
derived class.
The code in following example makes the concept of virtual function clear:
// Late Binding in C++ Program
#include <iostream>
using namespace std;
class Animals
{
public:
virtual void sound()
{ cout << "This is parent class" << endl; }
};
class Dogs : public Animals
{
public:
void sound()
{ cout << "Dogs bark" << endl; }
};
int main()
{
Animals *a;
Dogs d;
a= &d;
a -> sound();
return 0;
}
Output:
Dogs bark
Explanation of above example:
Since the function sound () of the base class is made virtual, the compiler now
performs late binding for this function.
Now, the function call will be matched to the function definition at runtime. Since the
compiler now identifies pointer “a” as referring to the object 'd' of the derived class
“Dogs”, it will call the sound() function of the class Dogs (derived class with output-
Dogs bark).
Another example using Virtual Function (Late Binding):
// Virtual Function concept is used
#include <iostream>
using namespace std;
class B
{
public:
virtual void show () // virtual function
{ cout<< "Base class \n"; }
};
class D: public B
{
public:
void show ()
{ cout<< "Derived class "; }
};
int main ( )
{
B * p; //pointer object of base class
B ob1;
D ob2;
p = & ob1; // address of base class provided to pointer object
p -> show ();
p = & ob2; // address of derived class provided to pointer object
p -> show ();
return 0;
}
Output
Base class
Derived class
Explanation of above example:
In above example, base class function is of type virtual. So, when the reference of
derived class is passed to base class pointers object then:
Because of virtual type function- base class show () has no real existence. It means, it
is not overriding now derived class show () output. So,
p = & ob2;
p -> show ();
It will print output: “derived class” instead of “base class”.

8.4 PURE VIRTUAL FUNCTION


Pure virtual Functions are virtual functions with no definition (have no body, just
blank body { }.
They start with virtual keyword.
Here is the syntax for a pure virtual function,
virtual void sound ( ) = 0;
or
virtual void sound ( )
{ }
So, a virtual function is a member function in base class that we suppose to redefine
in derived classes. In such case, no need to give body of a virtual function. So, assign
value 0 to virtual function and make it pure virtual function.
// Example of pure virtual function
#include <iostream>
using namespace std;
class Base //Abstract base class
{
public:
virtual void show() = 0; //Pure Virtual Function
};
class Derived:public Base
{
public:
void show()
{ cout << "Derived class"; }
};
int main()
{
Base *p;
Derived d;
p = &d;
p->show();
return 0;
}
Output
Derived class

8.5 ABSTRACT CLASS


A class which contains at least one Pure Virtual function in it is called abstract class.
Abstract classes are used to provide an Interface for its sub classes.
So, a class for which object is not created is called an abstract class. It means, in
inheritance base class is abstract class.
Some important Characteristics of Abstract Class
1. It cannot be instantiated, but pointers and references of Abstract class type can be
created.
2. Abstract class can have normal functions and also variables.
3. It can have a pure virtual function.
4. Abstract classes are mainly used for Upcasting, so that its derived classes can use
its interface.
5. Classes inheriting an Abstract Class must implement all pure virtual functions, or
else they will become Abstract too.

8.6 VIRTUAL DESTRUCTOR


▪ Virtual destructor means base class destructor can be created of virtual type.
▪ If we delete a derive class object using pointer to a base class that has a non-
virtual destructor then it produces results in undefined behavior.
▪ To correct this situation, the base class should be defined with a virtual destructor.
It means virtual destructor allows making destructor of base class as type virtual so
that when the program terminates then proper destruction of objects should be there.
This problem occurs in upcasting.
For example:
// Program without virtual destructor causing undefined behavior
#include <iostream>
using namespace std;
class B
{
public:
~B()
{ cout<<"base destruction of objects \n" ; }
};
class D : public B
{
public:
~D()
{ cout<<"derived destruction of objects \n" ; }
};
int main( )
{
D *d = new D();
B *b = d;
delete b;
return 0;
}
Output
base destruction of objects
In above example: the destruction of only base class object is performed but derived
class destructor is not called. So, it is undesirable process.
Solution is: create base class destructor as virtual destructor which guarantees that
the object of derived class is destructed properly, i.e., both base class and derived
class destructors are called. 
The code mentioned in example below makes the virtual destructor concept clear.
// Use of Virtual destructor Concept
#include <iostream>
using namespace std;
class B
{
public:
virtual ~ B ( )
{ cout<<"base destruction of objects \n" ; }
};
class D : public B
{
public:
~D()
{ cout<<"derived destruction of objects \n" ; }
};

int main()
{
D *d = new D();
B *b = d;
delete b;
return 0;
}
Output:
derived destruction of objects
base destruction of objects
Now, by making base class destructor as virtual, the destructors of both derived and
base class are called.

8.7 DIFFERENCE BETWEEN FUNCTION OVERLOADING AND FUNCTION


OVERRIDING

S Function Function Overriding


. Overloading
N
o
.
Function Overriding
Overloading can
Inherit occurs when
1 occur without
ance inheritance exists in
inheritance.
two classes.
Scope
of These are in same These are in different
2
functi scope. scopes.
ons
Overloaded functions
must differ in
Functi
function signature ie In overriding, function
on
3 either number of signatures must be
Signat
parameters or type of same.
ure
parameters should
differ.
Overloading is used
Overriding is needed
to have same name
Behavi when derived class
functions which
our of function has to do
4 behave differently
functi some added or
depending upon
ons different job than the
parameters passed to
base class function.
them.

◆◆◆◆◆
Chapter 9
Exception Handling
9.1 TRADITIONAL ERROR HANDLING

An exception means error in a program.


Error handling is a mechanism for detecting and then resolving various errors.
An error can be of following types:
▪ Development error
▪ Syntax error
▪ Semantic error
▪ Run-time error etc.
A development error can be prevented. Mostly it comes in syntax or semantics.
Syntax errors are mistakes or improper use of special characters.
Logical errors, also called bugs, occur when executed code does not produce the
expected or desired result. Perform debugging to capture these.A run-time error takes
place during the execution of a program, and usually happens because of invalid
input data.
9.2 EXCEPTION HANDLING MECHANISM
Exceptions provide a way to transfer control from one part of a program to another.
Exception handling mechanism consists of following parts:
1. Find the problem (Hit the exception)
2. Inform about its occurrence (Throw the exception)
3. Receive error information (Catch the exception)
4. Take proper action (Handle the exception)
C++ exception handling is built upon three keywords: 
try
catch
throw
Meaning of above keywords:
▪ try − A try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more catch blocks.
▪ catch − A program catches an exception with an exception handler at the place in a
program where programmer wants to handle the problem. The catch keyword
indicates the catching of an exception.
▪ throw − A program throws an exception when a problem shows up. This is done
using a throw keyword.
Suppose a block of code raises an exception.
A method catches an exception using a combination of the try and catch keywords. A
try/catch block is placed around the code that might generate an exception.
Code within a try/catch block is referred to as protected code.
The syntax for try/catch and throw is:
try
{
  statements;
  ... ... ...
  throw exception;
}
catch (type argument)
{
  statements;
  ... ... ...
}

Multiple catch exception


Multiple catch exception statements are used when a user wants to handle different
exceptions differently. For this, a user must include catch statements with different
declaration.
Syntax:
try
{
  body of try block
}

catch (type1 argument1)


{
  statements;
  ... ... ...
}
catch (type2 argument2)
{
  statements;
  ... ... ...
}
... ... ...
... ... ...
catch (typeN argumentN)
{
  statements;
  ... ... ...

Catch all exceptions


Sometimes, it may not be possible to design a separate catch block for each kind of
exception. In such cases, we can use a single catch statement that catches all kinds of
exceptions.
Syntax:
catch (...)
{
  statements;
  ... ... ...

Example of exception handling


// C++ program to divide two numbers using try catch block.
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int a,b;
cout << "Enter 2 numbers: ";
cin >> a >> b;
try
{ if (b != 0)
{ float div = (float) a/b;
if (div < 0)
throw 'e';
cout << "a/b = " << div;
}
else
throw b;
}
catch (int e)
{ cout << "Exception: Division by zero"; }
catch (char st)
{ cout << "Exception: Division is less than 1"; }
catch(...)
{ cout << "Exception: Unknown"; }
return 0;
}
Output:
Enter 2 numbers: 8 5
a/b = 1.6
Enter 2 numbers: 9 0
Exception: Division by zero
Enter 2 numbers: -1 10
Exception: Division is less than 1
Above program demonstrate how exceptions are handled in C++. This program
performs division operation.
Two numbers are entered by user for division operation.
If the dividend is zero, then division by zero will cause exception which is thrown into
catch block.
If the answer is less than 0, then exception "Division is less than 1" is thrown.
All other exceptions are handled by the last catch block throwing "Unknown"
exception.

9.3 RETHROWING AN EXCEPTION

It calls throw by itself, with no exception for rethrowing purpose.


Its syntax is: throw;
This causes current exception to be passed on to the next enclosing try/catch
sequence. Such exception is caught by a catch statement listed after that enclosing try
block. An exception can only be rethrown from within a catch block. When an
exception is rethrown, it is propagated outward to the next catch block.
//Example illustrating rethrowing
#include <iostream>
using namespace std;
void run (int x)
{
try
{ throw x; }
catch (int y)
{ cout <<"\nAn exception in a function";
throw; //rethrow y out of function
}
}
int main()
{
try
{ run(200); }
catch(int yy)
{ cout <<"\nCaught exception inside Main and called by throw of run function";
}
return 0;
}
Output
An exception in a function
Caught exception inside Main and called by throw of run function

9.4 ADVANTAGES OF EXCEPTION HANDLING


1. It provides clear cut distinction between the normal code and the error-handling
code. Such separation automatically results in less complex and more readable
code.
2. Programmers can deal with them at some level within the program.
3. If an error can't be dealt with at one level, then it will automatically be shown at
the next level, where it can be dealt with.
4. A logical grouping of error types Exceptions can be used to group together errors
that are related.

9.5 LIST OF SOME EXCEPTIONS IN C++


S Exception & Description
.
N
o
std::exception
1
An exception and parent class of all the standard C++ exceptions.
std::bad_alloc
2
This can be thrown by new.
std::bad_cast
3
This can be thrown by dynamic_cast.
std::bad_exception

4 This is useful device to handle unexpected exceptions in a C++


program.
std::bad_typeid
5
This can be thrown by typeid.
std::logic_error
6
An exception that theoretically can be detected by reading the code.
std::domain_error

7 This is an exception thrown when a mathematically invalid domain is


used.
std::invalid_argument
8
This is thrown due to invalid arguments.
std::length_error
9
This is thrown when a too big std::string is created.
std::out_of_range
1
This can be thrown by the 'at' method, for example a std::vector and
0
std::bitset<>::operator[]().
std::runtime_error
1
1 An exception that theoretically cannot be detected by reading the code.
std::overflow_error
1
2 This is thrown if a mathematical overflow occurs.
std::range_error
1
3 This is occurred when you try to store a value which is out of range.
std::underflow_error
1
4 This is thrown if a mathematical underflow occurs.

◆◆◆◆◆
Chapter 10
Templates and Generic
Programming
10.1 TEMPLATES AND GENERIC PROGRAMMING
▪ Templates are powerful features of C++, which allows a programmer to write
generic programs. 
▪ Templates are the foundation of generic programming. So it involves writing code in
a way that is independent of any particular type.
▪ A template is a blueprint or method for creating a generic class or a generic
function. It means we can create a single function or a class to work with different
data types using templates.
▪ It uses template concept.
▪ As a feature of C++, it allows functions and classes to operate with generic types.
▪ This allows a function or class to work on many different data types without being
rewritten for each one.
▪ We can use templates to define functions as well as classes. Therefore, it comes in
two forms.
o Function Template.
o Class Template.

10.2 FUNCTION TEMPLATES

A function template works in a similar way to a normal function with one key


difference. A function template can work with different data types at once but one
normal function can only work with one set of data types.
Use of function template is- write a code only once but can be reused repeatedly with
different values as argument type.
It provides high maintainable code.
Declaration of function template:

template<class T>
T someFunction( T arguments )
{
... .. ...
}
A function template starts with the keyword “template” followed by template
parameters inside <> and then function declaration.
So, in above syntax:
T is a template argument that accepts different data types (int, float, double),
and class is a keyword. When, an argument of a data type is passed
to someFunction( ), compiler generates a new version of someFunction() for the given
data type.
Example of Function Template:
//Function Template to find the largest number

#include <iostream>

using namespace std;

template <class T> // template function

T Large(T n1, T n2)

{ return (n1 > n2) ? n1 : n2; }

int main()

{ int i1, i2;

float f1, f2;

char c1, c2;

cout << "Enter two integers:\n";

cin >> i1 >> i2;

cout <<Large(i1, i2) <<" is larger." << endl;

cout << "\nEnter two floating-point numbers:\n";

cin >> f1 >> f2;

cout <<Large(f1, f2) <<" is larger." << endl;

cout << "\nEnter two characters:\n";

cin >> c1 >> c2;

cout<< Large(c1, c2) << " has larger ASCII value.";

return 0;
}

Output

Enter two integers:

10

10 is larger.

Enter two floating-point numbers:

12.4

10.2

12.4 is larger.

Enter two characters:

z has larger ASCII value.

Function templates are special functions which can operate with generic (nonspecific)


types. In C++ this can be achieved using template parameters.
It means, only once write a code for a function and easily use it for performing
function over different data types.
10.3 CLASS TEMPLATE
Same like function template, we can also define class templates.
The general form of a generic class declaration is as shown below:
template <class type> class class-name
{
.....
}
As mentioned above, type is the placeholder type name, which will be specified when
a class is instantiated.
Even we can define more than one generic data type by using a comma-separated list.
Benefits of class template:
Suppose a programmer wants to find:
▪ Sum of two integer values
▪ Sum of two float values
▪ Sum of two double values
One way to do same is increase length of program by adding different codes for
different functions like: Code 1 to find sum of two integer values, code 2 to find sum of
two float values and then code 3 to find sum of two double values. But it will consume
more time and is not logical in advance C++ programming.
So, the solution is: Use advance feature of C++ which is use of templates.
Following code is using the concept of template class to find sum of values of different
types.
//Class Template in C++

#include <iostream>

using namespace std;

template <class T>

class temp

{ private:

T a, b, c;

public:

void get ()

{ cout<<"\nEnter two numbers to find addition ";

cin>>a>>b; }

void sum ()

{ c = a+b;

cout<<"\nSUM = "<<c; }

};

int main()

temp <int> o1; //template call for int values of a,b

cout<<"\nGive integer values:";

o1.get ();

o1.sum ();

cout<<"\nGive double values:";

temp <double> o2; //template call for double values of a,b

o2.get ();

o2.sum ();

cout<<"\nGive float values:";

temp <float> o3; //template call for float values of a,b

o3.get ();
o3.sum ();

return 0;

}
Output:
Give integer values:                                                                                            
 Enter two numbers to find addition 10    20                                                         
SUM =  30                 
Give double values:                                                                                              
 Enter two numbers to find addition 200.22           300.33   
SUM =  500.55                                                                                                 
Give float values:                                                                                                    
Enter two numbers to find addition 2.2             3.9                                              

SUM =  6.1   

It is clear that same code has been utilized three times.


Firstly for adding integer values, then for adding double values and then for adding
float values.

◆◆◆◆◆
Chapter 11
Files
11.1 FILE STREAM

A file stream act as an interface between the program (where programmer writes code)
and the files (permanent storage on disk of computer).
The stream used to read from file is known as input stream. This file stream supplies
data to the program i.e. programmer reads from file.
The stream used to write into file is known as output stream. This file stream receives
data from the program i.e. programmer writes into file.
Figure below represents two types of stream with which either write in file or read from
file operations are performed.
There streams are:
1. Input stream
2. Output stream

Figure: Streams to operate with file


As shown in above figure:
Contents are written in a file or are read from a file.
C++ program is dealing in both cases.
Here, write () function is helping to write in a file and stream works at this time is
outputstream.
In same way- read () function is helping to read from a file and stream works at this
time is inputstream.

11.2 INTERACTION OF PROGRAM AND FILE


As a C++ programmer, we always use a particular IDE like in OOPs subject- usually
students use TurboC++, DevC++, Code Block etc.
All programs in this chapter have been executed in TurboC++ IDE.
When dealing with file then after performing write () operation in a specific named file,
it s easy to see whether file is stored in disk of computer or not. Take as example here:
Let TurboC++ is saved in Local C drive of a computer.
TurboC++ will have a folder Bin which will store files that a person has created with
the help of ofstream.
Assume the name of file used through code of C++ program was “mydata.txt” then
same named file can be checked manually in Bin directory of TurboC++. After opening
this file: contents of file will be same as written through C++ program.
Following figure explains same concept.

Output data after Write in disk file


processing Output file stream

C++ Program File on Disk

Input data for Read from disk file


Processing

Input file stream

Figure: File input and Output Stream

11.3 HIERARCHY OF FILE STREAM CLASSES


When a large amount of data is to be handled then storage is needed in a storage
device.
Files are useful to write (store) data in a file.
A file is a collection of characters or collection of related data. File handling in C++ is
very much similar to console input output operations but it differs as in file handling:
data is written into a file and read from a file.
Member functions of i/o stream classes:

Functions dealing with input stream are related with reading or extracting purpose
but functions dealing with output stream are related with writing or inserting purpose.

In both cases, open () and close () functions are common.

As shown in above figure:


▪ Class ios is the base class.
▪ The iostream class is derived from istream and ostream classes.
▪ The ifstream and ofstream are derived from istream and ostream.
▪ These classes handle input and output with the disk files.
▪ The fstream.h header file:
o contains a declaration of ifstream, ofstream and fstreamclasses.
▪ The iostream.h file contains:
o  istream, ostream and iostream classes and included in the program while doing
disk I/O operations.
▪ The filebuf class contains input and output operations with files.
▪ The streambuf class does not organize streams for input and output operations,
only derived classes of streambuf performs I/O operations. These derived classes
arrange a space for keeping input data and for sending output data. 
▪ The istream and ostream invokes the filebuf functions to perform the insertion or
extraction on the streams.
Details about I/O streams:
Stream Data
About it
Types:
It is output file stream.
ofstream It is used to create files and
To write information to files.
It is input file stream.
ifstream
It is used to read information from files.
It is file stream generally.
It has the capabilities of both ofstream and ifstream which
means it can:
fstream
Create files,
Write information to files, and
Read information from files.
It is File Stream Base.
fstreambase It acts as a base class for fstream, ifstream and ofstream. The
open() and close() functions are defined in fstreambase.

11.4 ERROR HANDLING DURING FILES OPERATIONS


While performing file operations, sometimes errors may also occur.
For example,
● Want to create a new file with a name but same named file already exists.
● A file being opened for reading but it does not exist.
● An attempt to read file but already reached at end of file and no more contents
which can be read.
● Insufficient disk space.
● Invalid file name with wrong format selected by user.
● An attempt to write in such a file which is read only.
● Device error.
Also other possibilities can arise during file operations which say that the chances of
invalid operation may have possibility.
To check for such errors and to ensure smooth processing, class ios provides four
important C++ Error Handling Functions which can be used to trap error.
Names of error handling functions
1) Eof ()
2) Fail ()
3) Bad ()
4) Good ()
Description:
1. Eof ()
● Its full form is end of file.
● It returns TRUE value when end of file is detected.
● Otherwise: returns FALSE value.
● It is used while reading a file from disk.
● In this case, ios:: eofbit is checked.
Use in program:
while (! fin.eof ()) // !fin.fail ()
{
//Read until end not approached
}

2. Fail ()
● It returns TRUE value if an operation (input or output) is unsuccessful means fail.
● Otherwise: returns FALSE value.
● It can be carried by reading the bits: ios::failbit,
● ios:: badbit and sometimes ios::hardfail of ios::state is checked.
Use in program:
while (!fin.fail () )
{
//Read until not fail
}

OR

if (fin.fail () )
{
// unable to open file
}

3. Bad ()
● It returns TRUE value if an unrecoverable error occurs or operation going to
perform is not valid.
● So TRUE value indicates bad operation and activation of bad ().
● Otherwise: returns FALSE value.
● Ios::badbit is checked.
Use in program:

if (fin.bad () )

{
// do not perform any operation and must report error
}
4. Good ()
● It returns TRUE value if everything with file is going in good way. So, TRUE value
indicates no error occurred.
● Otherwise: returns FALSE value.
● Overall it can be expressed if good () is active then it means all above functions (fail
(), eof (), bad ()) are false.
● Ios::goodbit is checked.

More about error handling functions:


C++ file streams inherit 'stream-state' members from the ios class that stores the
information on the status of a file that is being currently used.
The current state of the I/O system is held in an integer, in which the following flags
are encoded:

S
p
ec
ifi
c About it
N
a
m
e
eo
Is 1 when end of file is encountered,
fb
Otherwise it is 0
it
fa Is 1 when a non-fatal I/O error has occurred,
il Otherwise it is 0.
bi (The term non-fatal means not so serious to resolve on the
t support).
b
Is 1 when a fatal I/O error has occurred,
a
Otherwise it is 0.
d
It means something bad has occurred so it becomes active
bi
with value 1.
t
go Is 1 means everything going on is good.
o Otherwise it is 0.
d
bi
t

Code below illustrates the use of error handling functions:


ifstream fin; //fin used for reading a file
fin.open("text", ios::in); // file name if text, open it in read mode (ios::in)

while(!fin.fail()) // if open of file is not failed


{
…….. // process the file
}
if(fin.eof()) // if end of file reached
{
…..... // terminate the program
}
else if(fin.bad())
{
……… // report fatal error
}
else
{
fin.clear(); // clear error-state flags
………
}
Other cases:
//check end of file:
ifstream in (“data.txt”);
while (! in.eof ()) //read file data till end not reached
{
……. //read and print on screen
}

//illegal file name:


ifstream in (“****.txt”);
if(in.fail ())
{
……. //invalid file name
}

11.5 READING AND WRITING FILES


Basically a file can be used in two cases which are:
▪ Either read contents of already known file or
▪ Write in a file which allows write authority.
It is mandatory to use open () and close () functions for performing theses operations.
As already discussed:
If a file is with ifstream class then: only possible to read it.
If a file is with ofstream class then: only possible to write in it.
But:
If file is with fstream class then: read and write both operations are possible.
It is important to note that if write in a file is going on and file is showing open () for it
then do not allow any other write or read until it calls close (). Overall it can be
conceptualized that for reading and writing on a file, opening and closing file is
important.
Opening a file:
We need to tell the computer the purpose of opening our file. For example- to write in
a file, to read from a file, etc. These are different modes in which we can open a file.

S
.
Mode About it
N
o

ios::ap Opens a text file for appending. (appending


1
p means to add text at the end).

ios::at
2 Opens a file for output and move the read/write
e
control at the end of the file.
3 ios::in Opens a text file for reading.

ios::ou
4 Opens a text file for writing.
t

ios::bi
5 Binary file
nary

ios::tr Truncates the content before opening a file, if file


6
unc exists.

Open will work if file exists, otherwise open fails


means do not create a new file but pick if already
ios::no
7 created.
create
Only show required file if already existing
because new file create is not allowed.

Open will work if file does not already exists,


ios::no otherwise open fails means do not replace with
8 replac new one if same named file is already available.
e Only create required file if no copy already
existing because replace is not allowed.

Programs using File Handling in C++


Following file handling program illustrates the code of writing contents in a file.
//Writing in a file:
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
void main()
{
clrscr ();
ofstream ofile; //ofile is object to write in a file
ofile.open ("mydata.txt"); //mydata named file is opened for writing in it
ofile<<"Name: Kevi Chahal\n";
ofile<<"Age: 22 Months";
ofile.close ();
getch();
}
Above program will not print output on output screen but will store contents in a file.
This file is text document named “mydata” and is a type of permanent storage on hard
disk of computer. By default, it saves file in Bin directory of C++ IDE (let TurboC++).
The contents of mydata.txt file will be:
Name: Kevi Chahal
Age: 22 Months
Following file handling program illustrates the code of reading contents from a file.
//Reading a File:
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
void main()
{
clrscr ();
ifstream ifile; //ifile is object to read a file
ifile.open ("mydata.txt"); //Read file- mydata.txt
char ch;
while (!ifile.eof () )
{
ifile.get(ch);
cout<<ch;
}
ifile.close ();
getch();
}
Above example of reading contants of a file will print following contents on output
screen.
Name: Kevi Chahal
Age: 22 Months
In following example, use a file for both reading and writing purpose in same program.
This is possible in two ways: either use file modes or do it without file modes. File
modes explained in detail in next section.
Following example allows performing R/W (Reading/Writing) in a file without using
modes:
//Writing and reading contants of a file
#include <iostream.h>
#include <fstream.h>
#include<conio.h>
void main()
{
clrscr ();
char name[30];
int rollno;
ofstream ofile ("mydata1.txt"); //file is opened to write
cout<<"Enter Data to add in file: Name & Roll no";
cin>>name;
cin>>rollno;

ofile <<name; //entered name written in file


ofile<<rollno; //entered rollno written in file
ofile.close ();

cout<<"\n Contents of file are \n";


ifstream ifile ("mydata1.txt"); //file is opened to read
char ch;
while (!ifile.eof () )
{
ifile.get(ch);
cout<<ch;
}
ifile.close ();
getch();
}
Output:
Enter Data to add in file: Name & Roll no Jasrat 02
Contents of file are
Jasrat 2

Closing a file:
C++ automatically close and release all the allocated memory. But a programmer
should always close all the opened files.
In case, user wants to write in a file and in same program he wants to read whole
contents of this file.
In such case, firstly close the writing operation and then open same file again so that
reading will be performed after completion of writing in it. Same code is written in
above example. Two close functions are used: ofile.close () and ifile.close ();
Following code also tells about the use of close ( ) at the end after performing an
operation in an opened file.
//use of close ( ) function
#include <iostream.h>
#include <fstream.h>
void main()
{
ofstream file;
file.open ("example.txt");
file.close( );
getch();
}
Example illustrates Writing in a File:
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main()
{
char c, u;
char fname[10];
clrscr();
ofstream outfile; //outfile will be used for writing in a file
cout<< "Enter File Name:";
cin>>fname;
outfile.open(fname);
outfile<<”Jasrat”;
outfile<<”\n Age ”;
outfile<<”2”;
cout<< "Check file contents written recently ”;
outfile.close();
getch();
}
Output:
Enter File Name: contents.txt
Check files contents written recently
In contents.txt file, following contents will be written.
Jasrat
Age 2

Example illustrates Reading a File


#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main()
{
char fname[10];
char name [70];
clrscr();
ifstream infile; //infile will be used for reading from a file
cout<< "Enter file name:";
cin>>fname;
infile.open(fname);
while (! infile . eof ())
{
infile.get(name, 70);
cout<<name;
}
infile.close();
getch();
}
Output on screen:
Enter file name contents.txt
jasrat
age 2

11.6 ACCESSING RECORDS RANDOMLY (RANDOM ACCESS / UPDATING


FILES)

As updating records normally occur in the continuation of any file.


In same way- updating file stored in our disk through C++ program is also one of the
required tasks. It includes:
▪ Add a new item
▪ Delete an existing item
▪ Modify an existing item
For this purpose: random access of file is prior requirement.
In C++, random access is achieved by manipulating seekg(), seekp(), tellg() and tellp()
functions.
The seekg() and tellg() functions allow to set and examine the gets_pointer, and the
seekp() and tellp() functions perform these operations on the puts_pointer.
Each file maintains two pointers:
1. gets_pointer (in input mode file)
2. puts_pointer (in output mode file)
These pointers help to manage random access in file. That means moving directly to
any location in the file instead of moving through it sequentially.
Sometimes random access is the best choice.
For example, let a person has 40 student’s record in a file and he needs to modify one
value in 30th record, then using random access techniques it is comfortable to place
the file pointer at the beginning of record 30 and do updates as required in 30 th record.
On other side, if sequential method will be used, then unnecessarily he will have to go
through first twenty nine records in order to reach at record number 30.
So, concept of file position (or position inside a file) i.e. a pointer into the file is helpful.
While reading from and writing into a file, programmer should be very clear from
where (location inside the file) our process of reading or writing will start.

Functions used for Accessing File record randomly (Also called File Pointer and their
Manipulator)
Following is list of functions which can be used for randomly accessing records.

1) Seekg ()
2) Seekp ()
3) Tellg ()
4) Tellp ()

Character ‘g’ will get (read) contents from a random location as per need and
character ‘p’ will put (write) contents at a location as per need which can be accessed
randomly.
1. Seekg()
It moves gets pointer (input pointer) to a specified location.
For example:
infile.seekg (10);
Now after this statement, file pointer will point to 10 th byte from starting point.
Now, input pointer will read contents from 10th byte.
It can be written same as below:
infile.seekg(10L, ios::beg); //get contents from 10th byte.
infile.seekg(0, ios::end); //Go to the end of the file as mode is ios::end
2. Seekp()
It moves the puts pointer (output pointer) to a specified location.
For example:
Infile.seekp (15);
Now after this statement, file pointer will point to 15 th byte from starting point. Now, output
pointer will point to 15th byte for writing further contents.
The contents from 15th byte will be automatically shifted forward.
3. Tellg()
It tells about current position of get pointer.
Double size = infile.tellg ();
// It will tell (get) the file pointer position.
4. Tellp()
It tells about current position of put pointer.
double size = outfile.tellp ();
//It will tell (put) the file pointer position
Note:
Seekg () and tellg () functions combination can be used to determine the actual data
length of a file.
Common about functions seekg () and tellg ():
Both seekg () and tellg () work for ifstream objects because ifstream deals with reading
and get also indicates reading contents. Also both these functions allow user to set
and examine the gets_pointer,
Common about functions seekp() and tellp() :
Both seekp() and tellp() functions work for ofstream objects because ofstream deals
with writing and put also indicates writing contents. Also both thses functions perform
operations on the puts_pointer.
Name of Member Functions of Input Stream:
Input stream member functions are used for disk input. The member functions list is:
1) open () function for input streams
2) get ()
3) getline()
4) read()
5) seekg()
6) tellg()
7) close() function for input streams
Name of Member Functions of Output Stream:
Output stream member functions are used for screening output. The member
functions include:
1) open () function for output Streams
2) put ()
3) putline()
4) write()
5) seekp()
6) tellp()
7) close() function for output Streams.

◆◆◆◆◆

You might also like