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

MDU BCA- Object Oriented Programing(C++)

This document provides comprehensive handwritten notes on Object-Oriented Programming (OOP) concepts using C++. It covers topics such as procedural vs. object-oriented programming, characteristics of OOP, memory management, inheritance, polymorphism, exception handling, and user-defined data types. The notes are structured into sections that detail syntax, data types, functions, and various programming paradigms relevant to C++.

Uploaded by

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

MDU BCA- Object Oriented Programing(C++)

This document provides comprehensive handwritten notes on Object-Oriented Programming (OOP) concepts using C++. It covers topics such as procedural vs. object-oriented programming, characteristics of OOP, memory management, inheritance, polymorphism, exception handling, and user-defined data types. The notes are structured into sections that detail syntax, data types, functions, and various programming paradigms relevant to C++.

Uploaded by

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

1

MAHARSHI DAYANAND UNIVERSITY

Hand Writeen Notes in Easy Language

CREATED BY: ROHIT RATHOUR

CONTACT NO-7827646303
2

MDU BCA-4th SEMESTER


OBJECT ORIENTED PROGRAMING(C++)
INDEX
SECTION-I
Object Oriented Programing Concept:
 Procedural Language and Object Oriented
Approach
 Charactertics of OOPS
 User Defined Types
 Polymorphism
 Encapsulation
Getting Started with C++:
 Syntax
 Data Types
 Variables
 String
 Functions
 Namespace
 Exception
 Operator
 Flow Control
 Recursion
 Array and Pointer
 Structure
3

SECTION-II

Abstracting Mechanism:
 Classes
 Private and Public
 Constructor and Destructor
 Member Function
 Static Member
 Refrences

Memory Management:
 New
 Delete
 Object Copying
 Copy Constuctor
 Assignment Operator
 This Input/Output

SECTION-III
Inheritance and Polymorphism:
 Derived Class and Base Class
 Different Types of Inheritance
 Overriding Member Function
 Abstract Class
 Public and Private Inheritance
 Ambiguity in Multiple Inheritance
 Virtual Function
 Friend Function
 Static Function
4

SECTION-IV
Exception Handling:
 Exception and Derived Class
 Function Exception Declaration
 Unexpected Exception
 Exception When Handling Exception
 Resource Capure and Release
Template and Standard Template Library:
 Template Classes
 Template Declaration
 Template Function
 Namespace
 String
 Iterators
 Hashes
 Iostreams and other types
5

SECTION-I
Object Oriented Programing Concept
Procedural Language and Object Oriented
Approach:
Procedural Programming
It is defined as a programming language derived from the structure programming and
based on calling procedures. The procedures are the functions, routines, or
subroutines that consist of the computational steps required to be carried. It follows a
step-by-step approach in order to break down a task into a set of variables and
routines via a sequence of instructions.

During the program's execution, a procedure can be called at any point, either by other
procedures or by itself. The examples of procedural programming are ALGOL, COBOL,
BASIC, PASCAL, FORTRAN, and C.

As compared to object-oriented programming, procedural programming is less


secure. Procedural programming follows a top-down approach during the designing
of a program. It gives importance to the concept of the function and divides the large
programs into smaller parts or called as functions. Procedural programming is
straightforward. Unlike object-oriented programming, there are no access modifiers
introduced in procedural programming.

Object-oriented programming
Object-oriented programming is a computer programming design philosophy or
methodology that organizes/ models software design around data or objects rather
than functions and logic. It includes two words, "object" and "oriented". In a dictionary
object is an article or entity that exists in the real world. The meaning of oriented is
interested in a particular kind of thing or entity. In layman's terms, it is a programming
pattern that rounds around an object or entity.

The programming paradigm where everything is represented as an object is known as


a truly object-oriented programming language. Smalltalk is said to be the first truly
object-oriented programming language.
6

OOP is said to be the most popular programming model among developers. It is well
suited for programs that are large, complex, and actively updated or maintained. It
makes the development and maintenance of software easy by providing major
concepts such as abstraction, inheritance, polymorphism, and encapsulation. These
four are also the four pillars of an object-oriented programming system.

OOPs, provide the ability to simulate real-world events much more effectively. We can
provide the solution to real-world problems if we are using the Object-Oriented
Programming language. OOPs, provide data hiding, whereas, in Procedure-oriented
programming language, global data can be accessed from anywhere.

The examples of OOPs are - C#, Python, C++, Java, PHP, Scala, Perl, etc.

Procedural programming v/s Object-oriented


programming

Now, let's see the comparison between Procedural programming and object-oriented
programming. We are comparing both terms on the basis of some characteristics. The
difference between both languages are tabulated as follows -
7

S.no. On the Procedural Programming Object-oriented


basis of programming

1. Definition It is a programming language that Object-oriented


is derived from structure programming is a
programming and based upon the computer programming
concept of calling procedures. It design philosophy or
follows a step-by-step approach in methodology that
order to break down a task into a organizes/ models
set of variables and routines via a software design around
sequence of instructions. data or objects rather than
functions and logic.

2. Security It is less secure than OOPs. Data hiding is possible in


object-oriented
programming due to
abstraction. So, it is more
secure than procedural
programming.

3. Approach It follows a top-down approach. It follows a bottom-up


approach.

4. Data In procedural programming, data In OOP, objects can move


movement moves freely within the system and communicate with
from one function to another. each other via member
functions.

5. Orientation It is structure/procedure-oriented. It is object-oriented.

6. Access There are no access modifiers in The access modifiers in


modifiers procedural programming. OOP are named as private,
public, and protected.

7. Inheritance Procedural programming does not There is a feature of


have the concept of inheritance. inheritance in object-
oriented programming.
8

8. Code There is no code reusability It offers code reusability


reusability present in procedural by using the feature of
programming. inheritance.

9. Overloading Overloading is not possible in In OOP, there is a concept


procedural programming. of function overloading
and operator overloading.

10. Importance It gives importance to functions It gives importance to


over data. data over functions.

11. Virtual class In procedural programming, there In OOP, there is an


are no virtual classes. appearance of virtual
classes in inheritance.

12. Complex It is not appropriate for complex It is appropriate for


problems problems. complex problems.

13. Data hiding There is not any proper way for There is a possibility of
data hiding. data hiding.

14. Program In Procedural programming, a In OOP, a program is


division program is divided into small divided into small parts
programs that are referred to as that are referred to as
functions. objects.

15. Examples Examples of Procedural The examples of object-


programming include C, Fortran, oriented programming
Pascal, and VB. are -
.NET, C#, Python, Java,
VB.NET, and C++.

Charactetics of OOPs:
The characteristics of object oriented programming are as follows:

1. Objects
9

Objects are the basic run-time entities in an object-oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the
program must handle.The fundamental idea behind object oriented approach is to
combine both data and function into a single unit and these units are called objects.

The term objects means a combination of data and program that represent some
real word entity.

When a program executed, the object interact by sending messages to one another.
Each object contain data, and code to manipulate the data.

2. Class

A group of objects that share common properties for data part and some program
part are collectively called as class. In C ++ a class is a new data type that contains
member variables and member functions that operate on the variables.

The entire set of data and code of an object can be made a user-defined data type
with the help of a class. Objects are variable of the type class. Once a class has
been defined, we can create any number of objects belonging to that class.

When class is defined, objects are created as:

<classname><objectname>;

If employee has been defined as a class, then the statement

employee manager;

will create an object manager belonging to the class employee.

3. Encapsulation

Wrapping of data and functions together as a single unit is known as encapsulation.


By default data is not accessible to outside world and they are only accessible
through the functions which are wrapped in a class. Prevention of data from direct
access by the program is called data hiding or information hiding.

4. Data Abstraction

Abstraction refers to the act of representing essential features without including the
back ground details or explanation. Classes use the concept of abstraction and are
defined as a list of attributes such as size, weight, cost and functions to operate on
these attributes. They encapsulate all essential properties of the object that are to be
created. The attributes are called as data members as they hold data and the
functions which operate on these data are called as member functions.
10

Class use the concept of data abstraction so they are called abstract data type
(ADT).

5. Inheritance

Inheritance is the mechanism by which one class can inherit the properties of
another. It allows a hierarchy of classes to be build, moving from the most general
to the most specific. When one class is inherited by another, the class that is
inherited is called the base class. The inheriting class is called the derived class. In
general, the process of inheritance begins with the definition of a base class. The
base class defines all qualities that will be common to any derived class. . In OOPs,
the concept of inheritance provides the idea of reusability. In essence, the base
class represent the most general description of a set of traits. The derived class
inherits those general traits and adds properties that are specific to that class.

6. Polymorphism

Polymorphism comes from the Greek words “poly” and “morphism”. “poly”
means many and “morphism” means form i.e.. many forms. Polymorphism means
the ability to take more than one form. For example, an operation have different
behavior in different instances. The behavior depends upon the type of the data
used in the operation.

Different ways to achieving polymorphism in C++ program:

1) Function overloading

2) Operator overloading

It is able to express the operation of addition by a single operater say ‘+’. When
this is possible you use the expression x + y to denote the sum of x and y, for many
different types of x and y; integers , float and complex no. You can even define the
+ operation for two strings to mean the concatenation of the strings.

7. Dynamic Binding

Binding refers to the linking of a procedure call to the code to the executed in
response to the call. Dynamic binding means the code associated with a given
procedure call is not known until the time of the call at run-time. It is associated
with a polymorphic reference depends upon the dynamic type of that reference.
11

8. Message Passing

An object oriented program consists of a set of objects that communicate with each
other.

A message for an object is a request for execution of a procedure and therefore will
invoke a function (procedure) in the receiving object that generates the desired
result. Message passing involves specifying the name of the object, the name of the
function (message) and information to be sent.

User Defined Data Types:


Data types are means to identify the type of data and associated operations
of handling it. There are three types of data types:
1. Pre-defined DataTypes
2. Derived Data Types
3. User-defined DataTypes

In this article, the User-Defined DataType is explained:

User-Defined DataTypes:

The data types that are defined by the user are called the derived datatype
or user-defined derived data type.
These types include:
 Class
12

 Structure
 Union
 Enumeration
 Typedef defined DataType
Below is the detailed description of the following types:
1. Class: The building block of C++ that leads to Object-Oriented
programming is a Class. It is a user-defined data type, which holds its
own data members and member functions, which can be accessed and
used by creating an instance of that class. A class is like a blueprint for an
object.
Syntax:

Example:

// C++ program to demonstrate

// Class

#include <bits/stdc++.h>

using namespace std;

class Geeks {

// Access specifier
13

public:

// Data Members

string geekname;

// Member Functions()

void printname()

cout << "Geekname is: " << geekname;

};

int main()

// Declare an object of class geeks

Geeks obj1;

// accessing data member

obj1.geekname = "GeeksForGeeks";

// accessing member function


14

obj1.printname();

return 0;

Output:
Geekname is: GeeksForGeeks
2. Structure: A structure is a user defined data type in C/C++. A structure
creates a data type that can be used to group items of possibly different
types into a single type.
Syntax:
struct address {
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
Example:

// C++ program to demonstrate

// Structures in C++

#include <iostream>

using namespace std;

struct Point {
15

int x, y;

};

int main()

// Create an array of structures

struct Point arr[10];

// Access array members

arr[0].x = 10;

arr[0].y = 20;

cout << arr[0].x << ", " << arr[0].y;

return 0;

Output:
10, 20
3. Union: Like Structures, union is a user defined data type. In union, all
members share the same memory location. For example in the following
C program, both x and y share the same location. If we change x, we can
see the changes being reflected in y.
16

#include <iostream>

using namespace std;

// Declaration of union is same as the structures

union test {

int x, y;

};

int main()

// A union variable t

union test t;

// t.y also gets value 2

t.x = 2;

cout << "After making x = 2:"

<< endl

<< "x = " << t.x

<< ", y = " << t.y


17

<< endl;

// t.x is also updated to 10

t.y = 10;

cout << "After making Y = 10:"

<< endl

<< "x = " << t.x

<< ", y = " << t.y

<< endl;

return 0;

4. Output:
5. After making x = 2:
6. x = 2, y = 2
7. After making Y = 10:
8. x = 10, y = 10
9. Enumeration: Enumeration (or enum) is a user defined data type in C. It is
mainly used to assign names to integral constants, the names make a
program easy to read and maintain.
Syntax:
enum State {Working = 1, Failed = 0};

// Program to demonstrate working


18

// of enum in C++

#include <iostream>

using namespace std;

enum week { Mon,

Tue,

Wed,

Thur,

Fri,

Sat,

Sun };

int main()

enum week day;

day = Wed;

cout << day;


19

return 0;

Output:
2
10. Typedef : C++ allows you to define explicitly new data type names by
using the keyword typedef. Using typedef does not actually create a new
data class, rather it defines a name for an existing type. This can increase
the portability(the ability of a program to be used across different types of
machines; i.e., mini, mainframe, micro, etc; without much changes into
the code)of a program as only the typedef statements would have to be
changed. Using typedef one can also aid in self-documenting code by
allowing descriptive names for the standard data types.
Syntax:
typedef type name;
where type is any C++ data type and name is the new name for this data
type.
This defines another name for the standard type of C++.
Example:

// C++ program to demonstrate typedef

#include <iostream>

using namespace std;

// After this line BYTE can be used

// in place of unsigned char

typedef unsigned char BYTE;

int main()

{
20

BYTE b1, b2;

b1 = 'c';

cout << " " << b1;

return 0;

Output:
c

Polymorphism:
The term "Polymorphism" is the combination of "poly" + "morphs" which means many
forms. It is a greek word. In object-oriented programming, we use 3 main concepts:
inheritance, encapsulation, and polymorphism.

Real Life Example Of Polymorphism


Let's consider a real-life example of polymorphism. A lady behaves like a teacher in a
classroom, mother or daughter in a home and customer in a market. Here, a single
person is behaving differently according to the situations.

There are two types of polymorphism in C++:


21

o Compile time polymorphism: The overloaded functions are invoked by


matching the type and number of arguments. This information is available at
the compile time and, therefore, compiler selects the appropriate function at
the compile time. It is achieved by function overloading and operator
overloading which is also known as static binding or early binding. Now, let's
consider the case where function name and prototype is same.

1. class A // base class declaration.


2. {
3. int a;
4. public:
5. void display()
6. {
7. cout<< "Class A ";
8. }
9. };
10. class B : public A // derived class declaration.
11. {
12. int b;
13. public:
14. void display()
15. {
16. cout<<"Class B";
17. }
18. };

In the above case, the prototype of display() function is the same in both the base and
derived class. Therefore, the static binding cannot be applied. It would be great if the
appropriate function is selected at the run time. This is known as run time
polymorphism.

o Run time polymorphism: Run time polymorphism is achieved when the


object's method is invoked at the run time instead of compile time. It is achieved
by method overriding which is also known as dynamic binding or late binding.

Differences b/w compile time and run time


polymorphism.
22

Compile time polymorphism Run time polymorphism

The function to be invoked is known at The function to be invoked is


the compile time. known at the run time.

It is also known as overloading, early It is also known as overriding,


binding and static binding. Dynamic binding and late binding.

Overloading is a compile time Overriding is a run time


polymorphism where more than one polymorphism where more than
method is having the same name but one method is having the same
with the different number of name, number of parameters and
parameters or the type of the the type of the parameters.
parameters.

It is achieved by function overloading It is achieved by virtual functions


and operator overloading. and pointers.

It provides fast execution as it is It provides slow execution as it is


known at the compile time. known at the run time.

It is less flexible as mainly all the things It is more flexible as all the things
execute at the compile time. execute at the run time.

C++ Runtime Polymorphism Example


Let's see a simple example of run time polymorphism in C++.

// an example without the virtual keyword.

1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat(){
6. cout<<"Eating...";
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
23

12. void eat()


13. { cout<<"Eating bread...";
14. }
15. };
16. int main(void) {
17. Dog d = Dog();
18. d.eat();
19. return 0;
20. }

Output:

Eating bread...

C++ Run time Polymorphism Example: By using two


derived class
Let's see another example of run time polymorphism in C++ where we are having two
derived classes.

// an example with virtual keyword.

1. #include <iostream>
2. using namespace std;
3. class Shape { // base class
4. public:
5. virtual void draw(){ // virtual function
6. cout<<"drawing..."<<endl;
7. }
8. };
9. class Rectangle: public Shape // inheriting Shape class.
10. {
11. public:
12. void draw()
13. {
14. cout<<"drawing rectangle..."<<endl;
15. }
16. };
17. class Circle: public Shape // inheriting Shape class.
24

18.
19. {
20. public:
21. void draw()
22. {
23. cout<<"drawing circle..."<<endl;
24. }
25. };
26. int main(void) {
27. Shape *s; // base class pointer.
28. Shape sh; // base class object.
29. Rectangle rec;
30. Circle cir;
31. s=&sh;
32. s->draw();
33. s=&rec;
34. s->draw();
35. s=?
36. s->draw();
37. }

Output:

drawing...
drawing rectangle...
drawing circle...

Runtime Polymorphism with Data Members


Runtime Polymorphism can be achieved by data members in C++. Let's see an
example where we are accessing the field by reference variable which refers to the
instance of derived class.

1. #include <iostream>
2. using namespace std;
3. class Animal { // base class declaration.
4. public:
5. string color = "Black";
6. };
7. class Dog: public Animal // inheriting Animal class.
25

8. {
9. public:
10. string color = "Grey";
11. };
12. int main(void) {
13. Animal d= Dog();
14. cout<<d.color;
15. }

Output:

Black

Encapsulation:
A key idea in object-oriented programming (OOP) is encapsulation, which permits data
hiding and gives classes a way to isolate their implementation details from their clients.
C++ is an OOP language that provides several features for implementing
encapsulation, such as access specifiers and member functions. In this post, we'll
examine the C++ implementation of the encapsulation principle.

Encapsulation in C++:
The act of encapsulating involves combining data and the methods that manipulate it
into a single entity, referred to as a class. A class in C++ is a user-defined data type
that has member methods and data members. The member functions are methods
that work on the data members, which are variables that hold an object's state.

Access specifiers:
C++ provides three access specifiers, public, private, and protected, to control the
accessibility of class members. Anywhere in the programme can access the members
thanks to the public access specifier. Only the member functions of the class are
permitted access to the members thanks to the private access specifier. The member
functions of the class and its derived classes are able to access the members thanks to
the protected access specifier.

By default, all the members of a class are private. Therefore, we need to specify the
access specifiers explicitly to control the accessibility of the members.
26

Member functions:
Member functions are functions that are defined inside a class and operate on the data
members of that class. Because they are a component of the class, member functions
can access the private members of the class. Member functions can be classified into
two types: accessor functions and mutator functions.

Accessor functions are member functions that provide read-only access to the data
members of a class. Accessor functions do not modify the state of the object. Examples
of accessor functions include get() and display() functions.

Mutator functions are member functions that modify the state of the object by
changing the value of the data members. Mutator functions have access to and control
over a class's private members. Examples of mutator functions include set() and
update() functions.

Data hiding:
Data hiding is an important aspect of encapsulation that enables the data members of
a class to be hidden from the clients of the class. By making the data members private
and enabling accessor and mutator functions to access and modify the data members,
data hiding can be accomplished.

Here's a simple example of encapsulation in C++:

1. #include <iostream>
2. using namespace std;
3.
4. class Employee {
5. private:
6. int empId;
7. string empName;
8. float empSalary;
9.
10. public:
11. void setEmpId(int id) {
12. empId = id;
13. }
14.
15. void setEmpName(string name) {
16. empName = name;
27

17. }
18.
19. void setEmpSalary(float salary) {
20. empSalary = salary;
21. }
22.
23. int getEmpId() {
24. return empId;
25. }
26.
27. string getEmpName() {
28. return empName;
29. }
30.
31. float getEmpSalary() {
32. return empSalary;
33. }
34. };
35.
36. int main() {
37. Employee emp;
38. emp.setEmpId(101);
39. emp.setEmpName("John Doe");
40. emp.setEmpSalary(5000.0);
41.
42. cout << "Employee ID: " << emp.getEmpId() << endl;
43. cout << "Employee Name: " << emp.getEmpName() << endl;
44. cout << "Employee Salary: " << emp.getEmpSalary() << endl;
45.
46. return 0;
47. }

In this example, we have defined a class named Employee that has three private data
members: empId, empName, and empSalary. We have also defined six public member
functions: setEmpId(), setEmpName(), setEmpSalary(), getEmpId(), getEmpName(), and
getEmpSalary().
28

The values of the private data members are set using the set functions, which are
mutator functions. The values of the private data members are retrieved using the get
functions, which are accessor functions.

In the main() function, we have created an object of the Employee class and used the
mutator functions to set the values of the private data members. We have then used
the accessor functions to get the values of the private data members and printed them
to the console.

Output:

Employee ID: 101


Employee Name: John Doe
Employee Salary: 5000

In this way, encapsulation is implemented in C++ using access specifiers and member
functions. The private data members are hidden from the outside world, and the public
member functions provide a controlled interface to access and modify them.

Benefits of encapsulation:
Encapsulation provides several benefits, including:

o Improved code maintainability: Encapsulation helps in improving the code


maintainability by providing a clear separation between the implementation details of
a class and its clients.
o Data hiding: Encapsulation enables data hiding, which protects the data members of a
class from being accessed and modified by the clients of the class.
o Code reuse: Encapsulation helps in code reuse by providing a modular design that can
be easily extended and modified.
o Security: Encapsulation provides security by preventing unauthorized access to the
data members of a class.

Syntax in C++:
What is Syntax?
Syntax refers to the rules and regulations for writing statements in a
programming language. They can also be viewed as the grammatical rules
defining the structure of a programming language.
The C++ language also has its syntax for the functionalities it provides.
Different statements have different syntax specifying their usage but C++
29

programs also have basic syntax rules that are followed throughout all the
programs.

Basic Syntax of a C++ Program


We can learn about basic C++ Syntax using the following program.

The image above shows the basic C++ program that contains header files,
main function, namespace declaration, etc. Let’s try to understand them one
by one.

1. Header File

The header files contain the definition of the functions and macros we are
using in our program. They are defined on the top of the C++ program.
In line #1, we used the #include <iostream> statement to tell the compiler
to include an iostream header file library which stores the definition of the
cin and cout methods that we have used for input and output. #include is a
preprocessor directive using which we import header files.
Syntax:
#include <library_name>

2. Namespace

A namespace in C++ is used to provide a scope or a region where we define


identifiers. It is used to avoid name conflicts between two identifiers as only
unique names can be used as identifiers.
30

In line #2, we have used the using namespace std statement for specifying
that we will be the standard namespace where all the standard library
functions are defined.
Syntax:
using namespace std;

3. Main Function

Functions are basic building blocks of a C++ program that contains the
instructions for performing some specific task. Apart from the instructions
present in its body, a function definition also contains information about its
return type and parameters. To know more about C++ functions, please refer
to the article Functions in C++.
In line #3, we defined the main function as int main(). The main function is
the most important part of any C++ program. The program execution always
starts from the main function. All the other functions are called from the main
function. In C++, the main function is required to return some value indicating
the execution status.
Syntax:
int main() {

... code ....


return 0;
}

4. Blocks

Blocks are the group of statements that are enclosed within { } braces. They
define the scope of the identifiers and are generally used to enclose the body
of functions and control statements.
The body of the main function is from line #4 to line #9 enclosed within { }.
Syntax:
{

// Body of the Function

return 0;
}

5. Semicolons

As you may have noticed by now, each statement in the above code is
followed by a ( ; ) semicolon symbol. It is used to terminate each line of the
31

statement of the program. When the compiler sees this semicolon, it


terminates the operation of that line and moves to the next line.
Syntax:
any_statement ;

6. Identifiers

We use identifiers for the naming of variables, functions, and other user-
defined data types. An identifier may consist of uppercase and lowercase
alphabetical characters, underscore, and digits. The first letter must be an
underscore or an alphabet.
Example:
int num1 = 24;
int num2 = 34;
num1 & num2 are the identifiers and int is the data type.

7. Keywords

In the C++ programming language, there are some reserved words that are
used for some special meaning in the C++ program. It can’t be used for
identifiers.
For example, the words int, return, and using are some keywords used in
our program. These all have some predefined meaning in the C++ language.
There are total 95 keywords in C++. These are some keywords.
int void if while for
auto bool break

this static new true false


case char class

8. Basic Output cout

In line #7, we have used the cout method which is the basic output method
in C++ to output the sum of two numbers in the standard output stream
(stdout).
Syntax:
cout << result << endl;
Now, we have a better understanding of the basic syntax structure of the
above C++ program. Let’s try to execute this program and see if it works
correctly.
32

// C++ program to demonstrate the basic syntax

// Header File Library

#include <iostream>

// Standard Namespace

using namespace std;

// Main Function

int main()

// Body of the Function

// Declaration of Variable

int num1 = 24;

int num2 = 34;

int result = num1 + num2;

// Output
33

cout << result << endl;

// Return Statement

return 0;

Output
58
The above program runs correctly and displays the specified output because
we have followed the syntax rules of C++. We will learn more about these
basic elements later.

Object-Oriented Programming in C++


C++ programming language supports both procedural-oriented and object-
oriented programming. The above example is based on the procedural-
oriented programming paradigm. So let’s take another example to
discuss Object Oriented Programming in C++.
34

1. Class

A class is a template of an object. For example, the animal is a class & dog
is the object of the animal class. It is a user-defined data type. A class has its
own attributes (data members) and behavior (member functions). The first
letter of the class name is always capitalized & use the class keyword for
creating the class.
In line #3, we have declared a class named Calculate and its body expands
from line #3 to line #7.
Syntax:
class class_name{

// class body

};

2. Data Members & Member Functions

The attributes or data in the class are defined by the data members & the
functions that work on these data members are called the member functions.
Example:
class Calculate{

public:
int num1 = 50; // data member
int num2 = 30; // data member

// member function
int addition() {
int result = num1 + num2;
cout << result << endl;
}
};
In the above example, num1 and num2 are the data member & addition() is a
member function that is working on these two data members. There is a
keyword here public that is access modifiers. The access modifier decides
who has access to these data members & member functions. public access
modifier means these data members & member functions can get access by
anyone.
35

3. Object

The object is an instance of a class. The class itself is just a template that is
not allocated any memory. To use the data and methods defined in the class,
we have to create an object of that class.
They are declared in the similar way we declare variables in C++.
Syntax:
class_name object_name;
We use dot operator ( . ) for accessing data and methods of an object.
Now, let’s execute our code to see the output of the program.

 C++

#include <iostream>

using namespace std;

class Calculate{

// Access Modifiers

public:

// data member

int num1 = 50;

int num2 = 30;

// memeber function

int addition() {

int result = num1 + num2;


36

cout << result << endl;

};

int main() {

// object declaration

Calculate add;

// member function calling

add.addition();

return 0;

Output
80

Data Types in C++:


A data type specifies the type of data that a variable can store such as integer, floating,
character etc.
37

There are 4 types of data types in C++ language.

Types Data Types

Basic Data Type int, char, float, double, etc

Derived Data Type array, pointer, etc

Enumeration Data Type enum

User Defined Data Type structure

Basic Data Types


The basic data types 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 32 or 64 bit operating
system.
38

Let's see the basic data types. It size is given according to 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
39

long double 10 byte

Variable in C++:
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:

1. type variable_list;

The example of declaring 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=5,b=10; //declaring 2 variable of integer type


2. float f=30.8;
3. char c='A';

Rules for defining variables


A variable can have alphabets, digits and underscore.

A variable name can start with alphabet and underscore only. It can't start with digit.

No white space is allowed within variable name.

A variable name must not be any reserved word or keyword e.g. char, float etc.

Valid variable names:


40

1. int a;
2. int _ab;
3. int a30;

Invalid variable names:

1. int 4;
2. int x y;
3. int double;

String in C++:
C++ has in its definition a way to represent a sequence of characters as an
object of the class. This class is called std:: string. The string class stores
the characters as a sequence of bytes with the functionality of
allowing access to the single-byte character.

String vs Character Array

String Char Array

A string is a class that defines A character array is simply an array of


objects that be represented as a stream characters that can be terminated by a
of characters. null character.

In the case of strings, memory is allocated The size of the character array has to
dynamically. More memory can be be allocated statically, more memory
allocated at run time on demand. As no cannot be allocated at run time if
memory is preallocated, no memory is required. Unused allocated memory is
wasted. also wasted

As strings are represented as objects, no There is a threat of array decay in the


array decay occurs. case of the character array.
41

String Char Array

Strings are slower when compared to Implementation of character array is


implementation than character array. faster than std:: string.

String class defines a number of Character arrays do not


functionalities that allow manifold offer many inbuilt functions to
operations on strings. manipulate strings.

Operations on Strings
1) Input Functions

Function Definition

This function is used to store a stream of characters as entered by the


getline()
user in the object memory.

push_back() This function is used to input a character at the end of the string.

Introduced from C++11(for strings), this function is used to delete the


pop_back()
last character from the string.

Example:
 CPP

// C++ Program to demonstrate the working of

// getline(), push_back() and pop_back()

#include <iostream>

#include <string> // for string class


42

using namespace std;

// Driver Code

int main()

// Declaring string

string str;

// Taking string input using getline()

getline(cin, str);

// Displaying string

cout << "The initial string is : ";

cout << str << endl;

// Inserting a character

str.push_back('s');

// Displaying string

cout << "The string after push_back operation is : ";

cout << str << endl;


43

// Deleting a character

str.pop_back();

// Displaying string

cout << "The string after pop_back operation is : ";

cout << str << endl;

return 0;

Output
The initial string is :
The string after push_back operation is : s
The string after pop_back operation is :
Time Complexity: O(1)
Space Complexity: O(n) where n is the size of the string
2) Capacity Functions
Function Definition

This function returns the capacity allocated to the string, which can
be equal to or more than the size of the string. Additional space is
capacity()
allocated so that when the new characters are added to the string,
the operations can be done efficiently.

This function changes the size of the string, the size can be
resize()
increased or decreased.
44

Function Definition

length() This function finds the length of the string.

This function decreases the capacity of the string and makes it equal
to the minimum capacity of the string. This operation is useful to
shrink_to_fit()
save additional memory if we are sure that no further addition of
characters has to be made.

Example:
 CPP

// C++ Program to demonstrate the working of

// capacity(), resize() and shrink_to_fit()

#include <iostream>

#include <string> // for string class

using namespace std;

// Driver Code

int main()

// Initializing string

string str = "geeksforgeeks is for geeks";

// Displaying string
45

cout << "The initial string is : ";

cout << str << endl;

// Resizing string using resize()

str.resize(13);

// Displaying string

cout << "The string after resize operation is : ";

cout << str << endl;

// Displaying capacity of string

cout << "The capacity of string is : ";

cout << str.capacity() << endl;

// Displaying length of the string

cout << "The length of the string is :" << str.length()

<< endl;

// Decreasing the capacity of string

// using shrink_to_fit()

str.shrink_to_fit();
46

// Displaying string

cout << "The new capacity after shrinking is : ";

cout << str.capacity() << endl;

return 0;

Output
The initial string is : geeksforgeeks is for geeks
The string after resize operation is : geeksforgeeks
The capacity of string is : 26
The length of the string is :13
The new capacity after shrinking is : 13
Time Complexity: O(1)
Space Complexity: O(n) where n is the size of the string

3) Iterator Functions

Function Definition

begin() This function returns an iterator to the beginning of the string.

end() This function returns an iterator to the next to the end of the string.

rbegin() This function returns a reverse iterator pointing at the end of the string.

This function returns a reverse iterator pointing to the previous of


rend()
beginning of the string.
47

Function Definition

This function returns a constant iterator pointing to the beginning of the


cbegin()
string, it cannot be used to modify the contents it points-to.

This function returns a constant iterator pointing to the next of end of the
cend()
string, it cannot be used to modify the contents it points-to.

This function returns a constant reverse iterator pointing to the end of


crbegin()
the string, it cannot be used to modify the contents it points-to.

This function returns a constant reverse iterator pointing to the previous


crend() of beginning of the string, it cannot be used to modify the contents it
points-to.

Algorithm:
1. Declare a string
2. Try to iterate the string using all types of iterators
3. Try modification of the element of the string.
4. Display all the iterations.
Example:
 CPP

// C++ Program to demonstrate the working of

// begin(), end(), rbegin(), rend(), cbegin(), cend(), crbegin(), crend()

#include <iostream>

#include <string> // for string class

using namespace std;

// Driver Code
48

int main()

// Initializing string`

string str = "geeksforgeeks";

// Declaring iterator

std::string::iterator it;

// Declaring reverse iterator

std::string::reverse_iterator it1;

cout<<"Str:"<<str<<"\n";

// Displaying string

cout << "The string using forward iterators is : ";

for (it = str.begin(); it != str.end(); it++){

if(it == str.begin()) *it='G';

cout << *it;

cout << endl;

str = "geeksforgeeks";

// Displaying reverse string


49

cout << "The reverse string using reverse iterators is "

": ";

for (it1 = str.rbegin(); it1 != str.rend(); it1++){

if(it1 == str.rbegin()) *it1='S';

cout << *it1;

cout << endl;

str = "geeksforgeeks";

//Displaying String

cout<<"The string using constant forward iterator is :";

for(auto it2 = str.cbegin(); it2!=str.cend(); it2++){

//if(it2 == str.cbegin()) *it2='G';

//here modification is NOT Possible

//error: assignment of read-only location

//As it is a pointer to the const content, but we can inc/dec-rement the


iterator

cout<<*it2;

cout<<"\n";

str = "geeksforgeeks";
50

//Displaying String in reverse

cout<<"The reverse string using constant reverse iterator is :";

for(auto it3 = str.crbegin(); it3!=str.crend(); it3++){

//if(it2 == str.cbegin()) *it2='S';

//here modification is NOT Possible

//error: assignment of read-only location

//As it is a pointer to the const content, but we can inc/dec-rement the


iterator

cout<<*it3;

cout<<"\n";

return 0;

//Code modified by Balakrishnan R (rbkraj000)

Output
Str:geeksforgeeks
The string using forward iterators is : Geeksforgeeks
The reverse string using reverse iterators is : Skeegrofskeeg
The string using constant forward iterator is :geeksforgeeks
The reverse string using constant reverse iterator is
:skeegrofskeeg
Time Complexity: O(1)
Space Complexity: O(n) where n is the size of the string
4) Manipulating Functions:
51

Function Definition

This function copies the substring in the target character array


copy(“char
mentioned in its arguments. It takes 3 arguments, target char
array”, len,
array, length to be copied, and starting position in the string to
pos)
start copying.

swap() This function swaps one string with another

Example:
 CPP

// C++ Program to demonstrate the working of

// copy() and swap()

#include <iostream>

#include <string> // for string class

using namespace std;

// Driver Code

int main()

// Initializing 1st string

string str1 = "geeksforgeeks is for geeks";

// Declaring 2nd string


52

string str2 = "geeksforgeeks rocks";

// Declaring character array

char ch[80];

// using copy() to copy elements into char array

// copies "geeksforgeeks"

str1.copy(ch, 13, 0);

// Displaying char array

cout << "The new copied character array is : ";

cout << ch << endl;

// Displaying strings before swapping

cout << "The 1st string before swapping is : ";

cout << str1 << endl;

cout << "The 2nd string before swapping is : ";

cout << str2 << endl;

// using swap() to swap string content

str1.swap(str2);
53

// Displaying strings after swapping

cout << "The 1st string after swapping is : ";

cout << str1 << endl;

cout << "The 2nd string after swapping is : ";

cout << str2 << endl;

return 0;

Output
The new copied character array is : geeksforgeeks
The 1st string before swapping is : geeksforgeeks is for geeks
The 2nd string before swapping is : geeksforgeeks rocks
The 1st string after swapping is : geeksforgeeks rocks
The 2nd string after swapping is : geeksforgeeks is for geeks

Function in C++:
The function in C++ language is also known as procedure or subroutine in other
programming languages.

To perform any task, we can create function. A function can be called many times. It
provides modularity and code reusability.

Advantage of functions in C
There are many advantages of functions.
54

1) Code Reusability

By creating functions in C++, you can call it many times. So we don't need to write the
same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (531, 883 and 781) whether it is prime number
or not. Without using function, you need to write the prime number logic 3 times. So,
there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it
several times.

Types of Functions
There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C++ header files
such as ceil(x), cos(x), exp(x), etc.

2. User-defined functions: are the functions which are created by the C++
programmer, so that he/she can use it many times. It reduces complexity of a big
program and optimizes the code.
55

Declaration of a function
The syntax of creating function in C++ language is given below:

1. return_type function_name(data_type parameter...)


2. {
3. //code to be executed
4. }

C++ Function Example


Let's see the simple example of C++ function.

1. #include <iostream>
2. using namespace std;
3. void func() {
4. static int i=0; //static variable
5. int j=0; //local variable
6. i++;
7. j++;
8. cout<<"i=" << i<<" and j=" <<j<<endl;
9. }
10. int main()
11. {
12. func();
13. func();
14. func();
15. }

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

Namespace and Exception:


56

C++ Namespaces
Namespaces in C++ are used to organize too many classes so that it can be easy to
handle the application.

For accessing the class of a namespace, we need to use namespacename::classname.


We can use using keyword so that we don't have to use complete name all the time.

In C++, global namespace is the root namespace. The global::std will always refer to
the namespace "std" of C++ Framework.

C++ namespace Example


Let's see the simple example of namespace which include variable and functions.

1. #include <iostream>
2. using namespace std;
3. namespace First {
4. void sayHello() {
5. cout<<"Hello First Namespace"<<endl;
6. }
7. }
8. namespace Second {
9. void sayHello() {
10. cout<<"Hello Second Namespace"<<endl;
11. }
12. }
13. int main()
14. {
15. First::sayHello();
16. Second::sayHello();
17. return 0;
18. }

Output:

Hello First Namespace


Hello Second Namespace
57

C++ namespace example: by using keyword


Let's see another example of namespace where we are using "using" keyword so that
we don't have to use complete name for accessing a namespace program.

1. #include <iostream>
2. using namespace std;
3. namespace First{
4. void sayHello(){
5. cout << "Hello First Namespace" << endl;
6. }
7. }
8. namespace Second{
9. void sayHello(){
10. cout << "Hello Second Namespace" << endl;
11. }
12. }
13. using namespace First;
14. int main () {
15. sayHello();
16. return 0;
17. }

Output:

Hello First Namespace

Exception:
Exceptions provide a way to react to exceptional circumstances (like runtime errors) in programs by
transferring control to special functions called handlers.

To catch exceptions, a portion of code is placed under exception inspection. This is done by
enclosing that portion of code in a try-block. When an exceptional circumstance arises within that
block, an exception is thrown that transfers the control to the exception handler. If no exception is
thrown, the code continues normally and all handlers are ignored.

An exception is thrown by using the throw keyword from inside the try block. Exception handlers
are declared with the keyword catch, which must be placed immediately after the try block:
58

// exceptions An exception occ


#include <iostream>
using namespace std;

int main () {
try
{
throw 20;
}
catch (int e)
{
cout << "An exception occurred. Exception Nr. " << e <<
'\n';
}
return 0;
}
Edit & run on cpp.sh

The code under exception handling is enclosed in a try block. In this example this code simply
throws an exception:

1 throw 20;

A throw expression accepts one parameter (in this case the integer value 20), which is passed as
an argument to the exception handler.

The exception handler is declared with the catch keyword immediately after the closing brace of
the try block. The syntax for catch is similar to a regular function with one parameter. The type
of this parameter is very important, since the type of the argument passed by
the throw expression is checked against it, and only in the case they match, the exception is
caught by that handler.

Multiple handlers (i.e., catch expressions) can be chained; each one with a different parameter
type. Only the handler whose argument type matches the type of the exception specified in
the throw statement is executed.

If an ellipsis (...) is used as the parameter of catch, that handler will catch any exception no
matter what the type of the exception thrown. This can be used as a default handler that catches all
exceptions not caught by other handlers:

1 try {
2 // code here
3 }
4 catch (int param) { cout << "int exception"; }
5 catch (char param) { cout << "char exception"; }
6 catch (...) { cout << "default exception"; }

In this case, the last handler would catch any exception thrown of a type that is
59

neither int nor char.

After an exception has been handled the program, execution resumes after the try-catch block, not
after the throw statement!.

It is also possible to nest try-catch blocks within more external try blocks. In these cases, we
have the possibility that an internal catch block forwards the exception to its external level. This is
done with the expression throw; with no arguments. For example:

1 try {
2 try {
3 // code here
4 }
5 catch (int n) {
6 throw;
7 }
8 }
9 catch (...) {
10 cout << "Exception occurred";
11 }

Exception specification
Older code may contain dynamic exception specifications. They are now deprecated in C++, but still
supported. A dynamic exception specification follows the declaration of a function, appending
a throw specifier to it. For example:

1 double myfunction (char param) throw (int);

This declares a function called myfunction, which takes one argument of type char and
returns a value of type double. If this function throws an exception of some type other than int,
the function calls std::unexpected instead of looking for a handler or
calling std::terminate.

If this throw specifier is left empty with no type, this means that std::unexpected is called for
any exception. Functions with no throw specifier (regular functions) never
call std::unexpected, but follow the normal path of looking for their exception handler.

1 int myfunction (int param) throw(); // all exceptions call


2 unexpected
int myfunction (int param); // normal exception
handling
60

Standard exceptions
The C++ Standard library provides a base class specifically designed to declare objects to be thrown
as exceptions. It is called std::exception and is defined in the <exception> header. This
class has a virtual member function called what that returns a null-terminated character sequence
(of type char *) and that can be overwritten in derived classes to contain some sort of description
of the exception.

// using standard exceptions My exception happened.


#include <iostream>
#include <exception>
using namespace std;

class myexception: public


exception
{
virtual const char* what()
const throw()
{
return "My exception
happened";
}
} myex;

int main () {
try
{
throw myex;
}
catch (exception& e)
{
cout << e.what() << '\n';
}
return 0;
}
Edit & run on cpp.sh

We have placed a handler that catches exception objects by reference (notice the ampersand & after
the type), therefore this catches also classes derived from exception, like our myex object of
type myexception.

All exceptions thrown by components of the C++ Standard library throw exceptions derived from
this exception class. These are:

exception description

bad_alloc thrown by new on allocation failure

bad_cast thrown by dynamic_cast when it fails in a dynamic cast


61

bad_exception thrown by certain dynamic exception specifiers

bad_typeid thrown by typeid

bad_function_call thrown by empty function objects

bad_weak_ptr thrown by shared_ptr when passed a bad weak_ptr

Also deriving from exception, header <exception> defines two generic exception types that
can be inherited by custom exceptions to report errors:

exception description

logic_error error related to the internal logic of the program

runtime_error error detected during runtime

A typical example where standard exceptions need to be checked for is on memory allocation:

1 // bad_alloc standard exception


2 #include <iostream>
3 #include <exception>
4 using namespace std;
5
6 int main () {
7 try
8 {
9 int* myarray= new int[1000];
10 }
11 catch (exception& e)
12 {
13 cout << "Standard exception: " <<
14 e.what() << endl;
15 }
16 return 0;
}
Edit & run on cpp.sh

The exception that may be caught by the exception handler in this example is a bad_alloc.
Because bad_alloc is derived from the standard base class exception, it can be caught
(capturing by reference, captures all related classes).

Operator in C++:
An operator is simply a symbol that is used to perform operations. There can be many
types of operations like arithmetic, logical, bitwise etc.
62

There are following types of operators to perform different types of operations in C


language.

o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operator
o Unary operator
o Ternary or Conditional Operator
o Misc Operator

Precedence of Operators in C++


The precedence of operator species that which operator will be evaluated first and
next. The associativity specifies the operators 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;
63

The "data" variable will contain 105 because * (multiplicative operator) is evaluated
before + (additive operator).

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


64

Flow Control:
C++ is a programming language from a high level that is widely used for creating
applications and software. One of the most important concepts in C++ programming
is Flow Control, which refers to the ability to direct the flow of a program based on
specific conditions. This allows developers to control how their programs execute and
can help to make them more efficient and effective. In this article, we will see the
different types of flow control available in C++, how they work, and when they are
most appropriate.

Conditional Statements:
Conditional Statements are used in C++ to run a certain piece of program only if a
specific condition is met. There are generally three types of conditional statements in
C++: if, if-else, and switch.

if Statement:
The if statement is the simplest of the three and is used to run a certain piece of code
nly if a certain condition is true. For example:

C++ Code:

1. int x = 5;
2. if (x == 5) {
3. std::cout << "x is 5" << std::endl;
4. }

In this example, the block of code inside the curly braces will only be executed if the
condition inside the parentheses is true.

if-else Statement:
The if-else statement is used when we want to execute some code only if some
condition exists. If the given condition is true then code will be executed otherwise
else statement will be used to run other part of the code.For example:

C++ Code:

1. int x = 5;
2. if (x == 5) {
3. std::cout << "x is 5" << std::endl;
65

4. } else {
5. std::cout << "x is not 5" << std::endl;
6. }

In this example, if the condition inside the parentheses is true, the first block of code
will be executed. Otherwise, the second block of code will be executed.

switch Statement:
The switch statement is used to execute different blocks of code based on the value
of a variable. For example:

Pseudo Code:

1. switch (variable) {
2. case value1:
3. // code to execute if the variable is equal to value1
4. break;
5. case value2:
6. // code to execute if the variable is equal to value2
7. break;
8. // add more cases as needed
9. default:
10. // code to execute if the variable does not match any case
11. }

C++ code:

1. int x = 2;
2. switch (x) {
3. case 1:
4. std::cout << "x is 1" << std::endl;
5. break;
6. case 2:
7. std::cout << "x is 2" << std::endl;
8. break;
9. default:
10. std::cout << "x is not 1 or 2" << std::endl;
11. break;
66

12. }

In this example, the switch statement will execute the block of code associated with
the value of x. If x is 1, the first block of code will be executed. If x is 2, the second block
of code will be executed. If x is any other value, the default block of code will be
executed.

Loops:
Loops are used in C++ to execute a block of code multiple times, either until a certain
condition is met or for a specific number of times. There are generally three types of
loops in C++: while, do-while, and for.

While Loop:
The while loop is used to execute when we want to run some code for until some
specific condition matches. For example:

C++ Code:

1. int x = 0;
2. while (x < 5) {
3. std::cout << x << std::endl;
4. x++;
5. }

In this example, the while loop will continue to execute the block of code inside the
curly braces as long as x is less than 5. Each time the loop executes, the value of x will
be incremented by 1.

do-while Loop:
The do-while loop is the same as the while loop, but the condition is checked after
the first iteration of the loop. For example:

C++ Code:

1. int x = 0;
2. do {
3. std::cout << x << std::endl;
4. x++;
5. } while (x < 5);
67

In this example, the do-while loop will execute the block of code inside the curly
brackets, and then it will check the condition. So it will be executed a minimum of one
time.

for Loop:
The for loop allows a program to execute a piece of program a fixed number of times.
The syntax for the for loop is:

Pseudo Code:

1. for (initialization; condition; increment/decrement) {


2. // code to execute repeatedly
3. }

Here is an example that uses the for loop to print the numbers from 1 to 10:

C++ Code:

1. for (int i = 1; i <= 10; i++) {


2. cout << i << " ";
3. }

Recursion:
When function is called within the same function, it is known as recursion in C++. The
function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is known as
tail recursion. In tail recursion, we generally call the same function with return
statement.

Let's see a simple example of recursion.

1. recursionfunction(){
2. recursionfunction(); //calling self function
3. }
68

C++ Recursion Example


Let's see an example to print factorial number using recursion in C++ language.

1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. int factorial(int);
6. int fact,value;
7. cout<<"Enter any number: ";
8. cin>>value;
9. fact=factorial(value);
10. cout<<"Factorial of a number is: "<<fact<<endl;
11. return 0;
12. }
13. int factorial(int n)
14. {
15. if(n<0)
16. return(-1); /*Wrong value*/
17. if(n==0)
18. return(1); /*Terminating condition*/
19. else
20. {
21. return(n*factorial(n-1));
22. }
23. }

Output:

Enter any number: 5


Factorial of a number is: 120

We can understand the above program of recursive method call by the figure given
below:
69

Array and Pointer:


Like other programming languages, array in C++ is a group of similar types of
elements that have contiguous memory location.

In C++ std::array is a container that encapsulates fixed size arrays. In C++, array index
starts from 0. We can store only fixed set of elements in C++ array.

A collection of related data items stored in adjacent memory places is referred to as


an array in the C/C++ programming language or any other programming language
for that matter. Elements of an array can be accessed arbitrarily using its indices. They
can be used to store a collection of any type of primitive data type, including int, float,
double, char, etc. An array in C/C++ can also store derived data types like structures,
pointers, and other data types, which is an addition. The array representation in a
picture is provided below.

Advantages of C++ Array


o Code Optimization (less code)
o Random Access
70

o Easy to traverse data


o Easy to manipulate data
o Easy to sort data etc.

Disadvantages of C++ Array


o Fixed size

C++ Array Types


There are 2 types of arrays in C++ programming:

1. Single Dimensional Array


2. Multidimensional Array

C++ Single Dimensional Array


Let's see a simple example of C++ array, where we are going to create, initialize and
traverse array.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
6. //traversing array
7. for (int i = 0; i < 5; i++)
8. {
9. cout<<arr[i]<<"\n";
10. }
11. }

Output:

10
0
20
0
30

C++ Array Example: Traversal using foreach loop


71

We can also traverse the array elements using foreach loop. It returns array element
one by one.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
6. //traversing array
7. for (int i: arr)
8. {
9. cout<<i<<"\n";
10. }
11. }

Output:

10
20
30
40
50

Why do we need arrays?


With a limited number of objects, we can use regular variables (v1, v2, v3,..), but when
we need to hold many instances, managing them with normal variables becomes
challenging. To represent numerous instances in one variable, we use an array.

What happens if we try to access out of bound array?


The array's elements will be numbered 0 through 9 if we define an array of size 10.

We will have Undefined Behaviour if we attempt to access an element at an index


higher than 10, though.

C++ array with empty members


The maximum number of elements that can be stored in an array in C++ is n. What
will happen, though, if we store fewer than n elements?

For example,
72

1. // store only 3 elements in the array


2. int x[6] = {19, 10, 8};

The array x in this case is 6 elements wide. But we've only given it a three-element
initialization.

When that happens, the compiler fills in the empty spaces with random values. This
random value frequently appears as 0.

Important things to remember while using arrays in


C++
1. The array's indexes begin at 0. Meaning that the first item saved at index 0 is x[0].
2. The final element of an array with size n is kept at index (n-1). This example's final
element is x[5].
3. An array's elements have sequential addresses. Consider the scenario where
x[0beginning ]'s address is 2120.

The address of the subsequent element, x[1], will then be 2124, followed by x[2], 2128,
and so forth.

Each element in this case has a four-fold increase in size. This is due to the fact that int
has a 4 byte capacity.

What is two-dimensional array?


Each element in this kind of array is described by two indexes, the first of which denotes
a row and the second of which denotes a column.

As you can see, the components are arranged in a two-dimensional array using rows
and columns; there are I number of rows and j number of columns.

What is a multi-dimensional array?


A two-dimensional array is the most basic type of multidimensional array; it also
qualifies as a multidimensional array. There are no restrictions on the array's
dimensions.

How to insert it in array?


1. int mark[5] = {19, 10, 8, 17, 9}
73

2. // change 4th element to 9


3. mark[3] = 9;
4. // take input from the user
5. // store the value at third position
6. cin >> mark[2];
7. // take input from the user
8. // insert at ith position
9. cin >> mark[i-1];
10.
11. // print first element of the array
12. cout << mark[0];
13. // print ith element of the array
14. cout >> mark[i-1];

How to display the sum and average of array


elements?
1. #include <iostream>
2. using namespace std;
3. int main() {
4. // initialize an array without specifying the size
5. double numbers[] = {7, 5, 6, 12, 35, 27};
6. double sum = 0;
7. double count = 0;
8. double average;
9. cout << "The numbers are: ";
10. // print array elements
11. // use of range-based for loop
12. for (const double &n : numbers) {
13. cout << n << " ";
14. // calculate the sum
15. sum += n;
16. // count the no. of array elements
17. ++count;
18. }
19. // print the sum
20. cout << "\nTheir Sum = " << sum << endl;
74

21. // find the average


22. average = sum / count;
23. cout << "Their Average = " << average << endl;
24.
25. return 0;
26. }

Output:

The numbers are: 7 5 6 12 35 27


Their Sum = 92
Their Average = 15.3333

How to display array elements?


1. #include <iostream>
2. using namespace std;
3. int main() {
4. int numbers[5] = {7, 5, 6, 12, 35};
5. cout << "The numbers are: ";
6. // Printing array elements
7. // using range-based for loop
8. for (const int &n : numbers) {
9. cout << n << " ";
10. }
11. cout << "\nThe numbers are: ";
12. // Printing array elements
13. // using traditional for loop
14. for (int i = 0; i < 5; ++i) {
15. cout << numbers[i] << " ";
16. }
17. return 0;
18. }

Output:

The numbers are: 7 5 6 12 35


The numbers are: 7 5 6 12 35
75

Pointer:
The pointer in C++ language is a variable, it is also known as locator or indicator that
points to an address of a value.

The symbol of an address is represented by a pointer. In addition to creating and


modifying dynamic data structures, they allow programs to emulate call-by-reference.
One of the principal applications of pointers is iterating through the components of
arrays or other data structures. The pointer variable that refers to the same data type
as the variable you're dealing with has the address of that variable set to it (such as an
int or string).

Syntax
1. datatype *var_name;
2. int *ptr; // ptr can point to an address which holds int data

How to use a pointer?


1. Establish a pointer variable.
2. employing the unary operator (&), which yields the address of the variable, to assign a
pointer to a variable's address.
3. Using the unary operator (*), which gives the variable's value at the address provided
by its argument, one can access the value stored in an address.

Since the data type knows how many bytes the information is held in, we associate it
with a reference. The size of the data type to which a pointer points is added when we
increment a pointer.

Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving
strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.


76

3) It makes you able to access any memory location in the computer's memory.

Usage of pointer
There are many usage of pointers in C++ language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc()


functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces
the code and improves the performance.

Symbols used in pointer

Symbol Name Description

& (ampersand sign) Address operator Determine the address of a variable.

∗ (asterisk sign) Indirection operator Access the value of an address.

Declaring a pointer
The pointer in C++ language can be declared using ∗ (asterisk symbol).

1. int ∗ a; //pointer to int


2. char ∗ c; //pointer to char

Pointer Example
Let's see the simple example of using pointers printing the address and value.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int number=30;
77

6. int ∗ p;
7. p=&number;//stores the address of number variable
8. cout<<"Address of number variable is:"<<&number<<endl;
9. cout<<"Address of p variable is:"<<p<<endl;
10. cout<<"Value of p variable is:"<<*p<<endl;
11. return 0;
12. }

Output:

Address of number variable is:0x7ffccc8724c4


Address of p variable is:0x7ffccc8724c4
Value of p variable is:30

Pointer Program to swap 2 numbers without using 3rd


variable
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=20,b=10,∗p1=&a,∗p2=&b;
6. cout<<"Before swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
7. ∗p1=∗p1+∗p2;
8. ∗p2=∗p1-∗p2;
9. ∗p1=∗p1-∗p2;
10. cout<<"After swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
11. return 0;
12. }

Output:

Before swap: ∗p1=20 ∗p2=10


After swap: ∗p1=10 ∗p2=20

What are Pointer and string literals?


String literals are arrays of character sequences with null ends. The elements of a string
literal are arrays of type const char (because characters in a string cannot be modified)
plus a terminating null-character.
78

What is a void pointer?


This unique type of pointer, which is available in C++, stands in for the lack of a kind.
Pointers that point to a value that has no type are known as void pointers (and thus
also an undetermined length and undetermined dereferencing properties). This
indicates that void pointers are very flexible because they can point to any data type.
This flexibility has benefits. Direct dereference is not possible with these pointers.
Before they may be dereferenced, they must be converted into another pointer type
that points to a specific data type.

What is a invalid pointer?


A pointer must point to a valid address, not necessarily to useful items (like for arrays).
We refer to these as incorrect pointers. Additionally, incorrect pointers are uninitialized
pointers.

1. int *ptr1;
2. int arr[10];
3. int *ptr2 = arr+20;

Here, ptr1 is not initialized, making it invalid, and ptr2 is outside of the bounds of arr,
making it likewise weak. (Take note that not all build failures are caused by faulty
references.)

What is a null pointer?


A null pointer is not merely an incorrect address; it also points nowhere. Here are two
ways to mark a pointer as NULL:

1. int *ptr1 = 0;
2. int *ptr2 = NULL;

What is a pointer to a pointer?


In C++, we have the ability to build a pointer to another pointer, which might then
point to data or another pointer. The unary operator (*) is all that is needed in the
syntax for declaring the pointer for each level of indirection.

1. char a;
2. char *b;
3. char ** c;
4. a = 'g';
79

5. b = &a;
6. c = &b;

Here b points to a char that stores 'g', and c points to the pointer b.

What are references and pointers?


1. Call-By-Value
2. Call-By-Reference with a Pointer Argument
3. Call-By-Reference with a Reference Argument

Example

1. #include
2. using namespace std;
3. // Pass-by-Value
4. int square1(int n)
5. {cout << "address of n1 in square1(): " << &n << "\n";
6. n *= n;
7. return n;
8. }
9. // Pass-by-Reference with Pointer Arguments
10. void square2(int* n)
11. {
12. cout << "address of n2 in square2(): " << n << "\n";
13. *n *= *n;
14. }
15. // Pass-by-Reference with Reference Arguments
16. void square3(int& n)
17. {
18.
19. cout << "address of n3 in square3(): " << &n << "\n";
20. n *= n;
21. }
22. void example()
23. {
24. // Call-by-Value
25. int n1 = 8;
80

26. cout << "address of n1 in main(): " << &n1 << "\n";
27. cout << "Square of n1: " << square1(n1) << "\n";
28. cout << "No change in n1: " << n1 << "\n";
29.
30. // Call-by-Reference with Pointer Arguments
31. int n2 = 8;
32. cout << "address of n2 in main(): " << &n2 << "\n";
33. square2(&n2);
34. cout << "Square of n2: " << n2 << "\n";
35. cout << "Change reflected in n2: " << n2 << "\n";
36.
37. // Call-by-Reference with Reference Arguments
38. int n3 = 8;
39. cout << "address of n3 in main(): " << &n3 << "\n";
40. square3(n3);
41. cout << "Square of n3: " << n3 << "\n";
42. cout << "Change reflected in n3: " << n3 << "\n";
43. }
44. // Driver program
45. int main() { example(); }

Output
81

Structure:
In C++, classes and structs are blueprints that are used to create the instance of a class.
Structs are used for lightweight objects such as Rectangle, color, Point, etc.

Unlike class, structs in C++ are value type than reference type. It is useful if you have
data that is not intended to be modified after creation of struct.

C++ Structure is a collection of different data types. It is similar to the class that holds
different types of data.

The Syntax Of Structure

1. struct structure_name
2. {
3. // member declarations.
4. }

In the above declaration, a structure is declared by preceding the struct


keyword followed by the identifier(structure name). Inside the curly braces, we can
declare the member variables of different types. Consider the following situation:
82

1. struct Student
2. {
3. char name[20];
4. int id;
5. int age;
6. }

In the above case, Student is a structure contains three variables name, id, and age.
When the structure is declared, no memory is allocated. When the variable of a
structure is created, then the memory is allocated. Let's understand this scenario.

How to create the instance of Structure?


Structure variable can be defined as:

Student s;

Here, s is a structure variable of type Student. When the structure variable is created,
the memory will be allocated. Student structure contains one char variable and two
integer variable. Therefore, the memory for one char variable is 1 byte and two ints will
be 2*4 = 8. The total memory occupied by the s variable is 9 byte.

How to access the variable of Structure:


The variable of the structure can be accessed by simply using the instance of the
structure followed by the dot (.) operator and then the field of the structure.

For example:

1. s.id = 4;

In the above statement, we are accessing the id field of the structure Student by using
the dot(.) operator and assigns the value 4 to the id field.

C++ Struct Example


Let's see a simple example of struct Rectangle which has two data members width and
height.

1. #include <iostream>
2. using namespace std;
3. struct Rectangle
83

4. {
5. int width, height;
6.
7. };
8. int main(void) {
9. struct Rectangle rec;
10. rec.width=8;
11. rec.height=5;
12. cout<<"Area of Rectangle is: "<<(rec.width * rec.height)<<endl;
13. return 0;
14. }

Output:

Area of Rectangle is: 40

C++ Struct Example: Using Constructor and Method


Let's see another example of struct where we are using the constructor to initialize
data and method to calculate the area of rectangle.

1. #include <iostream>
2. using namespace std;
3. struct Rectangle {
4. int width, height;
5. Rectangle(int w, int h)
6. {
7. width = w;
8. height = h;
9. }
10. void areaOfRectangle() {
11. cout<<"Area of Rectangle is: "<<(width*height); }
12. };
13. int main(void) {
14. struct Rectangle rec=Rectangle(4,6);
15. rec.areaOfRectangle();
16. return 0;
17. }
84

Output:

Area of Rectangle is: 24

Structure v/s Class

Structure Class

If access specifier is not declared explicitly, If access specifier is not declared


then by default access specifier will be explicitly, then by default access
public. specifier will be private.

Syntax of Structure: Syntax of Class:

struct structure_name class class_name


{ {
// body of the structure. // body of the class.
} }

The instance of the structure is known as The instance of the class is known as
"Structure variable". "Object of the class".
85

SECTION-II

Abstracting Mechanism

Classes:
In C++, class is a group of similar objects. It is a template from which objects are
created. It can have fields, methods, constructors etc.

Let's see an example of C++ class that has three fields only.

1. class Student
2. {
3. public:
4. int id; //field or data member
5. float salary; //field or data member
6. String name;//field or data member
7. }

C++ Object and Class Example


Let's see an example of class that has two fields: id and name. It creates instance of the
class, initializes the object and prints the object value.

1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. };
8. int main() {
9. Student s1; //creating an object of Student
10. s1.id = 201;
11. s1.name = "Sonoo Jaiswal";
12. cout<<s1.id<<endl;
13. cout<<s1.name<<endl;
14. return 0;
86

15. }

Output:

201
Sonoo Jaiswal

C++ Class Example: Initialize and Display data


through method
Let's see another example of C++ class where we are initializing and displaying object
through method.

1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. void insert(int i, string n)
8. {
9. id = i;
10. name = n;
11. }
12. void display()
13. {
14. cout<<id<<" "<<name<<endl;
15. }
16. };
17. int main(void) {
18. Student s1; //creating an object of Student
19. Student s2; //creating an object of Student
20. s1.insert(201, "Sonoo");
21. s2.insert(202, "Nakul");
22. s1.display();
23. s2.display();
24. return 0;
25. }
87

Output:

201 Sonoo
202 Nakul

C++ Class Example: Store and Display Employee


Information
Let's see another example of C++ class where we are storing and displaying employee
information using method.

1. #include <iostream>
2. using namespace std;
3. class Employee {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. float salary;
8. void insert(int i, string n, float s)
9. {
10. id = i;
11. name = n;
12. salary = s;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1; //creating an object of Employee
21. Employee e2; //creating an object of Employee
22. e1.insert(201, "Sonoo",990000);
23. e2.insert(202, "Nakul", 29000);
24. e1.display();
25. e2.display();
26. return 0;
27. }
88

Output:

201 Sonoo 990000


202 Nakul 29000

Private and Public Class:

Public:
All the class members declared under public will be available to everyone.
The data members and member functions declared public can be accessed
by other classes too. The public members of a class can be accessed from
anywhere in the program using the direct member access operator (.) with
the object of that class.
Example:

// C++ program to demonstrate public

// access modifier

#include <iostream>

using namespace std;

// class definition

class Circle {

public:

double radius;

double compute_area()
89

return 3.14 * radius * radius;

};

// main function

int main()

Circle obj;

// accessing public data member outside class

obj.radius = 5.5;

cout << "Radius is: " << obj.radius << "\n";

cout << "Area is: " << obj.compute_area();

return 0;

Output:
Radius is: 5.5
Area is: 94.985
In the above program, the data member radius is public so we are allowed to
access it outside the class.
90

Private:
The class members declared as private can be accessed only by the
functions inside the class. They are not allowed to be accessed directly by
any object or function outside the class. Only the member functions or the
friend functions are allowed to access the private data members of a class.
Example:

// C++ program to demonstrate private

// access modifier

#include <iostream>

using namespace std;

class Circle {

// private data member

private:

double radius;

// public member function

public:

void compute_area(double r)

// member function can access private

// data member radius


91

radius = r;

double area = 3.14 * radius * radius;

cout << "Radius is: " << radius << endl;

cout << "Area is: " << area;

};

// main function

int main()

// creating object of the class

Circle obj;

// trying to access private data member

// directly outside the class

obj.compute_area(1.5);

return 0;

}
92

Output:
Radius is: 1.5
Area is: 7.065
Difference between Public and Private
Public Private

The class members declared as


All the class members declared under
private can be accessed only by
public will be available to everyone.
the functions inside the class.

Only the member functions or


The data members and member functions
the friend functions are allowed
declared public can be accessed by other
to access the private data
classes too.
members of a class.

The public members of a class can be


They are not allowed to be
accessed from anywhere in the program
accessed directly by any object
using the direct member access operator
or function outside the class.
(.) with the object of that class.

Constructor and Destructor:

Constructor:
A constructor is a particular member function having the same name as the class name.
It calls automatically whenever the object of the class is created.

Syntax:
The syntax of the constructor in C++ are given below.

1. class class_name
2. {
3. ……….
4. public
93

5. class_name ([parameter list])


6. {
7. ……………….
8. }
9. };

In the above-given syntax, class_name is the constructor's name, the public is an access
specifier, and the parameter list is optional.

Example of Constructor:
1. #include <iostream.h>
2. #include <conio.h>
3. using namespace std;
4. class hello { // The class
5. public: // Access specifier
6. hello () { // Constructor
7. cout << "Hello World! Program in C++ by using Constructor";
8. }
9. void display() {
10. cout <<"Hello World!" <<endl;
11. }
12. };
13. int main() {
14. hello myObj; /
15. return 0;
16. }

There are four types of constructors used in C++.

o Default constructor
o Dynamic constructor
o Parameterized constructor
o Copy constructor

Default Constructor: A constructor is a class which accepts no parameter and is called


a default constructor. If there is no constructor for a class, the compiler implicitly
creates a default constructor.

Following is the syntax of the default constructor:


94

1. class class_name {
2. private:
3. ………..
4. ………..
5. public:
6. class_name ()
7. {
8. …….
9. }
10. }

In this type of constructor, there are no arguments and parameter lists.

If no constructor is defined in the class, the compiler automatically creates the class's
default constructor.

Example:

1. class student {
2. private:
3. ………..
4. ………..
5. public:
6. student ()
7. {
8. …….
9. }
10. }

The default constructor for a class student is given below:

hello::hello()

Parameterised Constructor: A constructor is a class that can take parameters and is


called a parameterized constructor. It is used to initialize objects with a different set of
values.

Syntax of the Parameterised constructor is given below.

1. Class classname
2. {
95

3. …………;
4. …………;
5. Public:
6. Class name (parameter list)
7. {
8. ………….;
9. }
10. };

Here, we can define the parameter list of the constructor.

Copy Constructor: A particular constructor used for the creation of an existing object.
The copy constructor is used to initialize the thing from another of the same type.

Syntax:

Syntax of the copy constructor is given below.

1. Class (classname, &object)


2. {
3. ………….;
4. ………….;
5. }

In the above syntax, the object refers to a thing used to initialize another object.

Dynamic Constructor: This type of constructor can be used to allocate the memory
while creating the objects. The data members of an object after creation can be
initialized, called dynamic initialization.

Destructor in C++?
Destructors have the same class name preceded by (~) tilde symbol. It removes and
destroys the memory of the object, which the constructor allocated during the creation
of an object.

Syntax:
The syntax of destructor in C++ are given below.

1. class class_name
96

2. {
3. …………….;
4. …………….;
5. public:
6. xyz(); //constructor
7. ~xyz(); //destructor
8. };

Here, we use the tilde symbol for defining the destructor in C++ programming.

The Destructor has no argument and does not return any value, so it cannot be
overloaded.

Example of Destructor:
1. #include <iostream.h>
2. #include <conio.h>
3. using namespace std;
4. class Hello {
5. public:
6. //Constructor
7. Hello () {
8. cout<< "Constructor function is called" <<endl;
9. }
10. //Destructor
11. ~Hello () {
12. cout << "Destructor function is called" <<endl;
13. }
14. //Member function
15. void display() {
16. cout <<"Hello World!" <<endl;
17. }
18. };
19. int main(){
20. //Object created
21. Hello obj;
22. //Member function called
23. obj.display();
24. return 0;
97

25. }

Difference between Constructor and Destructor in C++


programming
Following table shows the various differences between constructor and destructor in
the C++ programming language:

Basis Constructor Destructor

Purpose of To allocate memory to the object, we To deallocate the memory that


use used a constructor in C++. the constructor allocated to an
object for this purpose, we use
the concept of destructor in C++.

Arguments It may or may not contain arguments. It cannot contain the arguments.

Calling It is called automatically whenever It is called automatically


the object of the class is created. whenever the program
terminates.

Memory Constructor occupies memory. The Destructor releases memory.

Return type It has return types. It doesn't have any return type.

Special While declaring constructor in the While declaring a destructor in


symbol C++ programming language, there is C++ programming language, a
no requirement of the special particular symbol is required, i.e.,
symbol. tilde symbol.

In numbers We can use more than one We cannot use more than one
constructor in our program. destructor in the program.

Inheritance It can be inherited. It cannot be inherited.

Overloading It can be overloaded. It cannot be overloaded.


98

Execution They are executed in successive They are executed in the


Order order. constructor's reverse order;
basically, they are the inverse of
the constructors.

Types Constructor has four types: Destructors have no classes.

o Default constructor
o Copy constructor
o Parameterized constructor
o Dynamic constructor

Declaration The following declaration is used for The following declaration is used
creating a constructor: for creating a destructor:
class class_name class class_name
{ {
………. …………….;
public …………….;
class_name ([parameter list]) public:
{ ~xyz();
………………. {
} …………
}; };

Member Function:
A class member function is a function that, like any other variable, is defined or
prototyped within the class declaration. It has access to all the members of the class
and can operate on any object of that class.

Let us use a member function to access the members of a previously created class
instead of directly accessing them.

1. class Dice {
2. public:
3. double L; // a dice's length
4. double B; // a dice's breadth
5. double H; // a dice's height
6. double getVolume(void); // Returns dice volume
7. };
99

Member functions can be defined either within the class definition or separately with
the scope resolution operator,:. Even if the inline specifier is not used, specifying a
member function within the class declaration declares the function inline. So, you may
either define the Volume() function as shown below.

1. class Dice {
2. public:
3. double L; // a dice's length
4. double B; // a dice's breadth
5. double H; // a dice's height
6. double getVolume(void) {
7. return L * B * H;
8. }
9. };

If we want, we may define the identical function outside of the class using the scope
resolution operator (::), as seen below.

1. double Dice::getVolume(void) {
2. return L * B * H;
3. }

The main thing to remember here is that we must use the class name exactly before
the :: operator. The dot operator (.) will be used to perform a member function on an
object and will only manipulate data relevant to that object as follows:

1. Dice myDice; // Generate an object


2. myDice.getVolume(); // Call the object's member function

Let us apply the techniques discussed above to set and get the values of various class
members of a class.

C++ Program:
1. #include <iostream>
2.
3. using namespace std;
4.
5. class Dice {
6. public:
7. double L; // a dice's length
100

8. double B; // a dice's breadth


9. double H; // a dice's height
10.
11. // Member functions declaration
12. double getVolume(void);
13. void setL(double length);
14. void setB(double breadth);
15. void setH(double height);
16. };
17.
18. // Member functions definitions
19. double Dice::getVolume(void) {
20. return L * B * H;
21. }
22.
23. void Dice::setL(double length)
24. {
25. L = length;
26. }
27. void Dice::setB(double breadth) {
28. B = breadth;
29. }
30. void Dice::setH(double height) {
31. H = height;
32. }
33.
34. // Main function
35. int main() {
36. Dice Dice1; // Declare Dice1 of type Dice
37. Dice Dice2; // Declare Dice2 of type Dice
38. double volume = 0.0; // here the volume of a Dice is stored
39.
40. // dice 1 specification
41. Dice1.setL(6.0);
42. Dice1.setB(7.0);
43. Dice1.setH(5.0);
44.
101

45. // Dice 2 specification


46. Dice2.setL(12.0);
47. Dice2.setB(13.0);
48. Dice2.setH(10.0);
49.
50. // volume of Dice 1
51. volume = Dice1.getVolume();
52. cout << "Volume of Dice1 : " << volume <<endl;
53.
54. // volume ofDice 2
55. volume = Dice2.getVolume();
56. cout << "Volume of Dice2 : " << volume <<endl;
57. return 0;
58. }

Output:

Volume of Dice1 : 210


Volume of Dice2 : 1560

Static Members:
The static is a keyword in the C and C++ programming language. We use the static
keyword to define the static data member or static member function inside and outside
of the class. Let's understand the static data member and static member function using
the programs.
102

Static data member


When we define the data member of a class using the static keyword, the data
members are called the static data member. A static data member is similar to the
static member function because the static data can only be accessed using the static
data member or static member function. And, all the objects of the class share the
same copy of the static member to access the static data.

Syntax

1. static data_type data_member;

Here, the static is a keyword of the predefined library.

The data_type is the variable type in C++, such as int, float, string, etc.

The data_member is the name of the static data.

Example 1: Let's create a simple program to access the static data members in the
C++ programming language.

1. #include <iostream>
2. #include <string.h>
3. using namespace std;
4. // create class of the Car
5. class Car
6. {
7. private:
8. int car_id;
9. char car_name[20];
10. int marks;
11.
12. public:
13. // declare a static data member
14. static int static_member;
15.
16. Car()
17. {
18. static_member++;
19. }
103

20.
21. void inp()
22. {
23. cout << " \n\n Enter the Id of the Car: " << endl;
24. cin >> car_id; // input the id
25. cout << " Enter the name of the Car: " << endl;
26. cin >> car_name;
27. cout << " Number of the Marks (1 - 10): " << endl;
28. cin >> marks;
29. }
30.
31. // display the entered details
32. void disp ()
33. {
34. cout << " \n Id of the Car: " << car_id;
35. cout << "\n Name of the Car: " << car_name;
36. cout << " \n Marks: " << marks;
37.
38. }
39. };
40.
41. // initialized the static data member to 0
42. int Car::static_member = 0;
43.
44. int main ()
45. {
46. // create object for the class Car
47. Car c1;
48. // call inp() function to insert values
49. c1. inp ();
50. c1. disp();
51.
52. //create another object
53. Car c2;
54. // call inp() function to insert values
55. c2. inp ();
56. c2. disp();
104

57.
58.
59. cout << " \n No. of objects created in the class: " << Car :: static_member <<endl;
60. return 0;
61. }

Output

Enter the Id of the Car:


101
Enter the name of the Car:
Ferrari
Number of the Marks (1 - 10):
10

Id of the Car: 101


Name of the Car: Ferrari
Marks: 10

Enter the Id of the Car:


205
Enter the name of the Car:
Mercedes
Number of the Marks (1 - 10):
9

Id of the Car: 205


Name of the Car: Mercedes
Marks: 9
No. of objects created in the class: 2
Static Member Functions
The static member functions are special functions used to access the static data
members or other static member functions. A member function is defined using the
static keyword. A static member function shares the single copy of the member
function to any number of the class' objects. We can access the static member function
using the class name or class' objects. If the static member function accesses any non-
static data member or non-static member function, it throws an error.

Syntax

1. class_name::function_name (parameter);

Here, the class_name is the name of the class.

function_name: The function name is the name of the static member function.

parameter: It defines the name of the pass arguments to the static member function.
105

Example 2: Let's create another program to access the static member function using
the class name in the C++ programming language.

1. #include <iostream>
2. using namespace std;
3. class Note
4. {
5. // declare a static data member
6. static int num;
7.
8. public:
9. // create static member function
10. static int func ()
11. {
12. return num;
13. }
14. };
15. // initialize the static data member using the class name and the scope resolution operator
16. int Note :: num = 5;
17.
18. int main ()
19. {
20. // access static member function using the class name and the scope resolution
21. cout << " The value of the num is: " << Note:: func () << endl;
22. return 0;
23. }

Output

The value of the num is: 5

Example 3: Let's create another program to access the static member function using
the class' object in the C++ programming language.

1. #include <iostream>
2. using namespace std;
3. class Note
4. {
5. // declare a static data member
106

6. static int num;


7.
8. public:
9. // create static member function
10. static int func ()
11. {
12. cout << " The value of the num is: " << num << endl;
13. }
14. };
15. // initialize the static data member using the class name and the scope resolution operator
16. int Note :: num = 15;
17.
18. int main ()
19. {
20. // create an object of the class Note
21. Note n;
22. // access static member function using the object
23. n.func();
24.
25. return 0;
26. }

Output

The value of the num is: 15

Example 4: Let's consider an example to access the static member function using the
object and class in the C++ programming language.

1. #include <iostream>
2. using namespace std;
3. class Member
4. {
5.
6. private:
7. // declaration of the static data members
8. static int A;
9. static int B;
10. static int C;
107

11.
12. // declare public access specifier
13. public:
14. // define the static member function
15. static void disp ()
16. {
17. cout << " The value of the A is: " << A << endl;
18. cout << " The value of the B is: " << B << endl;
19. cout << " The value of the C is: " << C << endl;
20. }
21. };
22. // initialization of the static data members
23. int Member :: A = 20;
24. int Member :: B = 30;
25. int Member :: C = 40;
26.
27. int main ()
28. {
29. // create object of the class Member
30. Member mb;
31. // access the static member function using the class object name
32. cout << " Print the static member through object name: " << endl;
33. mb. disp();
34. // access the static member function using the class name
35. cout << " Print the static member through the class name: " << endl;
36. Member::disp();
37. return 0;
38. }

Output

Print the static member through object name:


The value of the A is: 20
The value of the B is: 30
The value of the C is: 40
Print the static member through the class name:
The value of the A is: 20
The value of the B is: 30
The value of the C is: 40
108

References:
When a variable is declared as a reference, it becomes an alternative name
for an existing variable. A variable can be declared as a reference by putting
‘&’ in the declaration.
Also, we can define a reference variable as a type of variable that can act as
a reference to another variable. ‘&’ is used for signifying the address of a
variable or any memory. Variables associated with reference variables can
be accessed either by its name or by the reference variable associated with
it.
Prerequisite: Pointers in C++
Syntax:
data_type &ref = variable;
Example:
 C++

// C++ Program to demonstrate

// use of references

#include <iostream>

using namespace std;

int main()

int x = 10;

// ref is a reference to x.

int& ref = x;
109

// Value of x is now changed to 20

ref = 20;

cout << "x = " << x << '\n';

// Value of x is now changed to 30

x = 30;

cout << "ref = " << ref << '\n';

return 0;

Output:
x = 20
ref = 30
Applications of Reference in C++
There are multiple applications for references in C++, a few of them are
mentioned below:
1. Modify the passed parameters in a function
2. Avoiding a copy of large structures
3. In For Each Loop to modify all objects
4. For Each Loop to avoid the copy of objects
1. Modify the passed parameters in a function:
If a function receives a reference to a variable, it can modify the value of the
variable. For example, the following program variables are swapped using
references.
Example:
 C++

// C++ Program to demonstrate


110

// Passing of references as parameters

#include <iostream>

using namespace std;

// Function having parameters as

// references

void swap(int& first, int& second)

int temp = first;

first = second;

second = temp;

// Driver function

int main()

// Variables declared

int a = 2, b = 3;

// function called

swap(a, b);
111

// changes can be seen

// printing both variables

cout << a << " " << b;

return 0;

Output
3 2
2. Avoiding a copy of large structures:
Imagine a function that has to receive a large object. If we pass it without
reference, a new copy of it is created which causes a waste of CPU time and
memory. We can use references to avoid this.
Example:
struct Student {
string name;
string address;
int rollNo;
}

// If we remove & in below function, a new


// copy of the student object is created.
// We use const to avoid accidental updates
// in the function as the purpose of the function
// is to print s only.
void print(const Student &s)
{
cout << s.name << " " << s.address << " " << s.rollNo
<< '\n';
}
112

3. In For Each Loop to modify all objects:


We can use references for each loop to modify all elements.
Example:
 C++

// C++ Program for changing the

// values of elements while traversing

// using references

#include <iostream>

#include <vector>

using namespace std;

// Driver code

int main()

vector<int> vect{ 10, 20, 30, 40 };

// We can modify elements if we

// use reference

for (int& x : vect) {

x = x + 5;

}
113

// Printing elements

for (int x : vect) {

cout << x << " ";

cout << '\n';

return 0;

Output
15 25 35 45
4. For Each Loop to avoid the copy of objects:
We can use references in each loop to avoid a copy of individual objects
when objects are large.
Example:
 C++

// C++ Program to use references

// For Each Loop to avoid the

// copy of objects

#include <iostream>

#include <vector>
114

using namespace std;

// Driver code

int main()

// Declaring vector

vector<string> vect{ "geeksforgeeks practice",

"geeksforgeeks write",

"geeksforgeeks ide" };

// We avoid copy of the whole string

// object by using reference.

for (const auto& x : vect) {

cout << x << '\n';

return 0;

Output
geeksforgeeks practice
geeksforgeeks write
geeksforgeeks ide
115

References vs Pointers
Both references and pointers can be used to change the local variables of
one function inside another function. Both of them can also be used to save
copying of big objects when passed as arguments to functions or returned
from functions, to get efficiency gain. Despite the above similarities, there are
the following differences between references and pointers.
1. A pointer can be declared as void but a reference can never be void For
example
int a = 10;
void* aa = &a; // it is valid
void& ar = a; // it is not valid
2. The pointer variable has n-levels/multiple levels of indirection i.e. single-
pointer, double-pointer, triple-pointer. Whereas, the reference variable has
only one/single level of indirection. The following code reveals the mentioned
points:
3. Reference variables cannot be updated.
4. Reference variable is an internal pointer.
5. Declaration of a Reference variable is preceded with the ‘&’ symbol ( but
do not read it as “address of”).
Example:
 C++

// C++ Program to demonstrate

// references and pointers

#include <iostream>

using namespace std;

// Driver Code

int main()

// simple or ordinary variable.


116

int i = 10;

// single pointer

int* p = &i;

// double pointer

int** pt = &p;

// triple pointer

int*** ptr = &pt;

// All the above pointers differ in the value they store

// or point to.

cout << "i = " << i << "\t"

<< "p = " << p << "\t"

<< "pt = " << pt << "\t"

<< "ptr = " << ptr << '\n';

// simple or ordinary variable

int a = 5;

int& S = a;
117

int& S0 = S;

int& S1 = S0;

// All the references do not differ in their

// values as they all refer to the same variable.

cout << "a = " << a << "\t"

<< "S = " << S << "\t"

<< "S0 = " << S0 << "\t"

<< "S1 = " << S1 << '\n';

return 0;

Output
i = 10 p = 0x7ffecfe7c07c pt = 0x7ffecfe7c080 ptr =
0x7ffecfe7c088
a = 5 S = 5 S0 = 5 S1 = 5

Limitations of References

1. Once a reference is created, it cannot be later made to reference another


object; it cannot be reset. This is often done with pointers.
2. References cannot be NULL. Pointers are often made NULL to indicate
that they are not pointing to any valid thing.
3. A reference must be initialized when declared. There is no such restriction
with pointers.
Due to the above limitations, references in C++ cannot be used for
implementing data structures like Linked List, Tree, etc. In Java, references
don’t have the above restrictions and can be used to implement all data
structures. References being more powerful in Java is the main reason Java
doesn’t need pointers.
118

Advantages of using References

1. Safer: Since references must be initialized, wild references like wild


pointers are unlikely to exist. It is still possible to have references that
don’t refer to a valid location (See questions 5 and 6 in the below
exercise)
2. Easier to use: References don’t need a dereferencing operator to access
the value. They can be used like normal variables. The ‘&’ operator is
needed only at the time of declaration. Also, members of an object
reference can be accessed with the dot operator (‘.’), unlike pointers
where the arrow operator (->) is needed to access members.
Together with the above reasons, there are a few places like the copy
constructor argument where a pointer cannot be used. Reference must be
used to pass the argument in the copy constructor. Similarly, references
must be used for overloading some operators like ++.

Exercise with Answers


Question 1 :
 C++

#include <iostream>

using namespace std;

int& fun()

static int x = 10;

return x;

int main()

{
119

fun() = 30;

cout << fun();

return 0;

Output
30
Question 2
 C++

#include <iostream>

using namespace std;

int fun(int& x) { return x; }

int main()

cout << fun(10);

return 0;

Output:
./3337ee98-ae6e-4792-8128-7c879288221f.cpp: In function 'int
main()':
./3337ee98-ae6e-4792-8128-7c879288221f.cpp:8:19: error: invalid
initialization of non-const reference of type 'int&' from an rvalue
of type 'int'
cout << fun(10);
120

^
./3337ee98-ae6e-4792-8128-7c879288221f.cpp:4:5: note: in passing
argument 1 of 'int fun(int&)'
int fun(int& x) { return x; }
Question 3
 C++

#include <iostream>

using namespace std;

void swap(char*& str1, char*& str2)

char* temp = str1;

str1 = str2;

str2 = temp;

int main()

char* str1 = "GEEKS";

char* str2 = "FOR GEEKS";

swap(str1, str2);

cout << "str1 is " << str1 << '\n';

cout << "str2 is " << str2 << '\n';


121

return 0;

Output
str1 is FOR GEEKS
str2 is GEEKS
Question 4
 C++

#include <iostream>

using namespace std;

int main()

int x = 10;

int* ptr = &x;

int&* ptr1 = ptr;

Output:
./18074365-ebdc-4b13-81f2-cfc42bb4b035.cpp: In function 'int
main()':
./18074365-ebdc-4b13-81f2-cfc42bb4b035.cpp:8:11: error: cannot
declare pointer to 'int&'
int&* ptr1 = ptr;
Question 5
 C++
122

#include <iostream>

using namespace std;

int main()

int* ptr = NULL;

int& ref = *ptr;

cout << ref << '\n';

Output:
timeout: the monitored command dumped core
/bin/bash: line 1: 34 Segmentation fault timeout 15s
./372da97e-346c-4594-990f-14edda1f5021 < 372da97e-346c-4594-990f-
14edda1f5021.in
Question 6
 C++

#include <iostream>

using namespace std;

int& fun()

int x = 10;
123

return x;

int main()

fun() = 30;

cout << fun();

return 0;

Output
0
124

Memory Management

New:
new operator

The new operator denotes a request for memory allocation on the Free Store.
If sufficient memory is available, a new operator initializes the memory and
returns the address of the newly allocated and initialized memory to the pointer
variable.
Syntax to use new operator
pointer-variable = new data-type;
Here, the pointer variable is the pointer of type data-type. Data type could be
any built-in data type including array or any user-defined data type including
structure and class.
Example:
// Pointer initialized with NULL
// Then request memory for the variable
int *p = NULL;
p = new int;

OR

// Combine declaration of pointer


// and their assignment
int *p = new int;
Initialize memory: We can also initialize the memory for built-in data types
using a new operator. For custom data types, a constructor is required (with
the data type as input) for initializing the value. Here’s an example of the
initialization of both data types :
pointer-variable = new data-type(value);
Example:
 C++

int* p = new int(25);


125

float* q = new float(75.25);

// Custom data type

struct cust

int p;

cust(int q) : p(q) {}

cust() = default;

//cust& operator=(const cust& that) = default;

};

int main()

// Works fine, doesn’t require constructor

cust* var1 = new cust;

//OR

// Works fine, doesn’t require constructor

var1 = new cust();


126

// Notice error if you comment this line

cust* var = new cust(25);

return 0;

Allocate a block of memory: a new operator is also used to allocate a


block(an array) of memory of type data type.
pointer-variable = new data-type[size];
where size(a variable) specifies the number of elements in an array.
Example:
int *p = new int[10]
Dynamically allocates memory for 10 integers continuously of type int and
returns a pointer to the first element of the sequence, which is assigned top(a
pointer). p[0] refers to the first element, p[1] refers to the second element, and
so on.

Normal Array Declaration vs Using new


There is a difference between declaring a normal array and allocating a block
of memory using new. The most important difference is, that normal arrays are
deallocated by the compiler (If the array is local, then deallocated when the
function returns or completes). However, dynamically allocated arrays always
remain there until either they are deallocated by the programmer or the
program terminates.
What if enough memory is not available during runtime?
If enough memory is not available in the heap to allocate, the new request
indicates failure by throwing an exception of type std::bad_alloc, unless
“nothrow” is used with the new operator, in which case it returns a NULL
pointer (scroll to section “Exception handling of new operator” in this article).
Therefore, it may be a good idea to check for the pointer variable produced by
the new before using its program.
int *p = new(nothrow) int;
if (!p)
{
127

cout << "Memory allocation failed\n";


}

Delete:
Since it is the programmer’s responsibility to deallocate dynamically allocated
memory, programmers are provided delete operator in C++ language.
Syntax:
// Release memory pointed by pointer-variable
delete pointer-variable;
Here, the pointer variable is the pointer that points to the data object created
by new.
Examples:
delete p;
delete q;
To free the dynamically allocated array pointed by pointer variable, use the
following form of delete:
// Release block of memory
// pointed by pointer-variable
delete[] pointer-variable;

Example:

// It will free the entire array


// pointed by p.
delete[] p;

 CPP

// C++ program to illustrate dynamic allocation

// and deallocation of memory using new and delete

#include <iostream>

using namespace std;

int main ()
128

// Pointer initialization to null

int* p = NULL;

// Request memory for the variable

// using new operator

p = new(nothrow) int;

if (!p)

cout << "allocation of memory failed\n";

else

// Store value at allocated address

*p = 29;

cout << "Value of p: " << *p << endl;

// Request block of memory

// using new operator

float *r = new float(75.25);

cout << "Value of r: " << *r << endl;


129

// Request block of memory of size n

int n = 5;

int *q = new(nothrow) int[n];

if (!q)

cout << "allocation of memory failed\n";

else

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

q[i] = i+1;

cout << "Value store in block of memory: ";

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

cout << q[i] << " ";

// freed the allocated memory

delete p;

delete r;

// freed the block of allocated memory

delete[] q;
130

return 0;

Output
Value of p: 29
Value of r: 75.25
Value store in block of memory: 1 2 3 4 5
Time Complexity: O(n), where n is the given memory size.

Object Copying:
object copying is creating a copy of an existing object, a unit of data in object-oriented
programming. The resulting object is called an object copy or simply copy of the original object.
Copying is basic but has subtleties and can have significant overhead. There are several ways to
copy an object, most commonly by a copy constructor or cloning. Copying is done mostly so the
copy can be modified or moved, or the current value preserved. If either of these is unneeded, a
reference to the original data is sufficient and more efficient, as no copying occurs.
Objects in general store composite data. While in simple cases copying can be done by
allocating a new, uninitialized object and copying all fields (attributes) from the original object, in
more complex cases this does not result in desired behavior.

Methods of copying
The design goal of most objects is to give the resemblance of being made out of one monolithic
block even though most are not. As objects are made up of several different parts, copying
becomes nontrivial. Several strategies exist to treat this problem.
Consider an object A, which contains fields xi (more concretely, consider if A is a string and xi is
an array of its characters). There are different strategies for making a copy of A, referred to
as shallow copy and deep copy. Many languages allow generic copying by one or either strategy,
defining either one copy operation or separate shallow copy and deep copy operations.[1] Note
that even shallower is to use a reference to the existing object A, in which case there is no new
object, only a new reference.
The terminology of shallow copy and deep copy dates to Smalltalk-80.[2] The same distinction
holds for comparing objects for equality: most basically there is a difference between identity
(same object) and equality (same value), corresponding to shallow equality and (1 level) deep
equality of two object references, but then further whether equality means comparing only the
fields of the object in question or dereferencing some or all fields and comparing their values in
turn (e.g., are two linked lists equal if they have the same nodes, or if they have same
values?).[clarification needed]
131

Shallow copy[edit]
One method of copying an object is the shallow copy. In that case a new object B is created, and
the fields values of A are copied over to B.[3][4][5] This is also known as a field-by-field
copy,[6][7][8] field-for-field copy, or field copy.[9] If the field value is a reference to an object (e.g., a
memory address) it copies the reference, hence referring to the same object as A does, and if
the field value is a primitive type it copies the value of the primitive type. In languages without
primitive types (where everything is an object), all fields of the copy B are references to the same
objects as the fields of original A. The referenced objects are thus shared, so if one of these
objects is modified (from A or B), the change is visible in the other. Shallow copies are simple
and typically cheap, as they can usually be implemented by simply copying the bits exactly.

Deep copy[edit]

A deep copy in progress.

A deep copy having been completed.

An alternative is a deep copy, meaning that fields are dereferenced: rather than references to
objects being copied, new copy objects are created for any referenced objects, and references to
these are placed in B.

Implementation
Nearly all object-oriented programming languages provide some way to copy objects. As most
languages do not provide most objects for programs, a programmer must define how an object
should be copied, just as they must define if two objects are identical or even comparable in the
first place. Many languages provide some default behavior.
How copying is solved varies from language to language, and what concept of an object it has.

Lazy copy
A lazy copy is an implementation of a deep copy. When initially copying an object, a (fast)
shallow copy is used. A counter is also used to track how many objects share the data. When the
program wants to modify an object, it can determine if the data is shared (by examining the
counter) and can do a deep copy if needed.
132

Lazy copy looks to the outside just as a deep copy, but takes advantage of the speed of a
shallow copy whenever possible. The downside are rather high but constant base costs because
of the counter. Also, in certain situations, circular references can cause problems.
Lazy copy is related to copy-on-write.

Copy Constructor:
A Copy constructor is an overloaded constructor used to declare and initialize an
object from another object.

Copy Constructor is of two types:


o Default Copy constructor: The compiler defines the default copy constructor. If the
user defines no copy constructor, compiler supplies its constructor.
o User Defined constructor: The programmer defines the user-defined constructor.

Syntax Of User-defined Copy Constructor:


1. Class_name(const class_name &old_object);

Consider the following situation:

1. class A
2. {
3. A(A &x) // copy constructor.
4. {
5. // copyconstructor.
6. }
7. }

In the above case, copy constructor can be called in the following ways:
133

Let's see a simple example of the copy constructor.

// program of the copy constructor.

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. public:
6. int x;
7. A(int a) // parameterized constructor.
8. {
9. x=a;
10. }
11. A(A &i) // copy constructor
12. {
13. x = i.x;
14. }
15. };
16. int main()
17. {
18. A a1(20); // Calling the parameterized constructor.
19. A a2(a1); // Calling the copy constructor.
20. cout<<a2.x;
21. return 0;
22. }

Output:

20

When Copy Constructor is called


Copy Constructor is called in the following scenarios:

o When we initialize the object with another existing object of the same class type. For
example, Student s1 = s2, where Student is the class.
134

o When the object of the same class type is passed by value as an argument.
o When the function returns the object of the same class type by value.

Two types of copies are produced by the constructor:


o Shallow copy

o Deep copy

Shallow Copy
o The default copy constructor can only produce the shallow copy.
o A Shallow copy is defined as the process of creating the copy of an object by copying
data of all the member variables as it is.

Let's understand this through a simple example:

1. #include <iostream>
2.
3. using namespace std;
4.
5. class Demo
6. {
7. int a;
8. int b;
9. int *p;
10. public:
11. Demo()
12. {
13. p=new int;
14. }
15. void setdata(int x,int y,int z)
16. {
17. a=x;
18. b=y;
19. *p=z;
20. }
21. void showdata()
22. {
135

23. std::cout << "value of a is : " <<a<< std::endl;


24. std::cout << "value of b is : " <<b<< std::endl;
25. std::cout << "value of *p is : " <<*p<< std::endl;
26. }
27. };
28. int main()
29. {
30. Demo d1;
31. d1.setdata(4,5,7);
32. Demo d2 = d1;
33. d2.showdata();
34. return 0;
35. }

Output:

value of a is : 4
value of b is : 5
value of *p is : 7

In the above case, a programmer has not defined any constructor, therefore, the
statement Demo d2 = d1; calls the default constructor defined by the compiler. The
default constructor creates the exact copy or shallow copy of the existing object. Thus,
the pointer p of both the objects point to the same memory location. Therefore, when
the memory of a field is freed, the memory of another field is also automatically freed
as both the fields point to the same memory location. This problem is solved by
the user-defined constructor that creates the Deep copy.

Deep copy
Deep copy dynamically allocates the memory for the copy and then copies the actual
value, both the source and copy have distinct memory locations. In this way, both the
136

source and copy are distinct and will not share the same memory location. Deep copy
requires us to write the user-defined constructor.

Let's understand this through a simple example.

1. #include <iostream>
2. using namespace std;
3. class Demo
4. {
5. public:
6. int a;
7. int b;
8. int *p;
9.
10. Demo()
11. {
12. p=new int;
13. }
14. Demo(Demo &d)
15. {
16. a = d.a;
17. b = d.b;
18. p = new int;
19. *p = *(d.p);
20. }
21. void setdata(int x,int y,int z)
22. {
23. a=x;
24. b=y;
25. *p=z;
26. }
27. void showdata()
28. {
29. std::cout << "value of a is : " <<a<< std::endl;
30. std::cout << "value of b is : " <<b<< std::endl;
31. std::cout << "value of *p is : " <<*p<< std::endl;
32. }
33. };
137

34. int main()


35. {
36. Demo d1;
37. d1.setdata(4,5,7);
38. Demo d2 = d1;
39. d2.showdata();
40. return 0;
41. }

Output:

value of a is : 4
value of b is : 5
value of *p is : 7

In the above case, a programmer has defined its own constructor, therefore the
statement Demo d2 = d1; calls the copy constructor defined by the user. It creates
the exact copy of the value types data and the object pointed by the pointer p. Deep
copy does not create the copy of a reference type variable.

Differences b/w Copy constructor and Assignment


operator(=)

Copy Constructor Assignment Operator

It is an overloaded constructor. It is a bitwise operator.

It initializes the new object with the existing It assigns the value of one object
object. to another object.
138

Syntax of copy constructor: Syntax of Assignment operator:


Class_name(const class_name &object_name) Class_name a,b;
{ b = a;
// body of the constructor.
}

The assignment operator is


o The copy constructor is invoked when
invoked when we assign the
the new object is initialized with the existing object to a new object.
existing object.
o The object is passed as an argument to
the function.
o It returns the object.

Both the existing object and new object shares Both the existing object and new
the different memory locations. object shares the same memory
location.

If a programmer does not define the copy If we do not overload the "="
constructor, the compiler will automatically operator, the bitwise copy will
generate the implicit default copy constructor. occur.

Assignment Operator:
139

Assignment operators are used to assigning value to a variable. The left side
operand of the assignment operator is a variable and right side operand of
the assignment operator is a value. The value on the right side must be of
the same data-type of the variable on the left side otherwise the compiler will
raise an error.
Different types of assignment operators are shown below:
 “=”: This is the simplest assignment operator. This operator is used to
assign the value on the right to the variable on the left.
For example:
 a = 10;
 b = 20;
 ch = 'y';
 “+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator
first adds the current value of the variable on left to the value on the right
and then assigns the result to the variable on the left.
Example:
 (a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
 “-=”This operator is combination of ‘-‘ and ‘=’ operators. This operator
first subtracts the current value of the variable on left from the value on
140

the right and then assigns the result to the variable on the left.
Example:
 (a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
 “*=”This operator is combination of ‘*’ and ‘=’ operators. This operator
first multiplies the current value of the variable on left to the value on the
right and then assigns the result to the variable on the left.
Example:
 (a *= b) can be written as (a = a * b)
If initially value stored in a is 5. Then (a *= 6) = 30.
 “/=”This operator is combination of ‘/’ and ‘=’ operators. This operator first
divides the current value of the variable on left by the value on the right
and then assigns the result to the variable on the left.
Example:
 (a /= b) can be written as (a = a / b)
If initially value stored in a is 6. Then (a /= 2) = 3.
Below example illustrates the various Assignment Operators:

 C
 C++

// C program to demonstrate

// working of Assignment operators

#include <stdio.h>

int main()

// Assigning value 10 to a
141

// using "=" operator

int a = 10;

printf("Value of a is %d\n", a);

// Assigning value by adding 10 to a

// using "+=" operator

a += 10;

printf("Value of a is %d\n", a);

// Assigning value by subtracting 10 from a

// using "-=" operator

a -= 10;

printf("Value of a is %d\n", a);

// Assigning value by multiplying 10 to a

// using "*=" operator

a *= 10;

printf("Value of a is %d\n", a);

// Assigning value by dividing 10 from a

// using "/=" operator

a /= 10;
142

printf("Value of a is %d\n", a);

return 0;

Output:
Value of a is 10
Value of a is 20
Value of a is 10
Value of a is 100
Value of a is 10

This Input/Output:
C++ comes with libraries that provide us with many ways for performing input
and output. In C++ input and output are performed in the form of a sequence
of bytes or more commonly known as streams.
 Input Stream: If the direction of flow of bytes is from the device(for
example, Keyboard) to the main memory then this process is called input.
 Output Stream: If the direction of flow of bytes is opposite, i.e. from main
memory to device( display screen ) then this process is called output.
143

Header files available in C++ for Input/Output operations are:


1. iostream: iostream stands for standard input-output stream. This header
file contains definitions of objects like cin, cout, cerr, etc.
2. iomanip: iomanip stands for input-output manipulators. The methods
declared in these files are used for manipulating streams. This file
contains definitions of setw, setprecision, etc.
3. fstream: This header file mainly describes the file stream. This header file
is used to handle the data being read from a file as input or data being
written into the file as output.
4. bits/stdc++: This header file includes every standard library. In
programming contests, using this file is a good idea, when you want to
reduce the time wasted in doing chores; especially when your rank is time
sensitive. To know more about this header file refer this article.
In C++ after the header files, we often use ‘using namespace std;‘. The
reason behind it is that all of the standard library definitions are inside the
namespace std. As the library functions are not defined at global scope, so in
order to use them we use namespace std. So, that we don’t need to write
STD:: at every line (eg. STD::cout etc.). To know more refer this article.
The two instances cout in C++ and cin in C++ of iostream class are used
very often for printing outputs and taking inputs respectively. These two are
144

the most basic methods of taking input and printing output in C++. To use cin
and cout in C++ one must include the header file iostream in the program.
This article mainly discusses the objects defined in the header
file iostream like the cin and cout.
 Standard output stream (cout): Usually the standard output device is
the display screen. The C++ cout statement is the instance of the
ostream class. It is used to produce output on the standard output device
which is usually the display screen. The data needed to be displayed on
the screen is inserted in the standard output stream (cout) using the
insertion operator(<<).
 C++

#include <iostream>

using namespace std;

int main()

char sample[] = "GeeksforGeeks";

cout << sample << " - A computer science portal for geeks";

return 0;

Output:
GeeksforGeeks - A computer science portal for geeks
Time Complexity: O(1)
Auxiliary Space: O(1)
145

In the above program, the insertion operator(<<) inserts the value of the
string variable sample followed by the string “A computer science portal for
geeks” in the standard output stream cout which is then displayed on the
screen.
 standard input stream (cin): Usually the input device in a computer is
the keyboard. C++ cin statement is the instance of the class istream and
is used to read input from the standard input device which is usually a
keyboard.
The extraction operator(>>) is used along with the object cin for reading
inputs. The extraction operator extracts the data from the object cin which
is entered using the keyboard.
 C++

#include <iostream>

using namespace std;

int main()

int age;

cout << "Enter your age:";

cin >> age;

cout << "\nYour age is: " << age;

return 0;

Input :
18
Output:
146

Enter your age:


Your age is: 18
Time Complexity: O(1)
Auxiliary Space: O(1)
The above program asks the user to input the age. The object cin is
connected to the input device. The age entered by the user is extracted from
cin using the extraction operator(>>) and the extracted data is then stored in
the variable age present on the right side of the extraction operator.
 Un-buffered standard error stream (cerr): The C++ cerr is the standard
error stream that is used to output the errors. This is also an instance of
the iostream class. As cerr in C++ is un-buffered so it is used when one
needs to display the error message immediately. It does not have any
buffer to store the error message and display it later.
 The main difference between cerr and cout comes when you would like to
redirect output using “cout” that gets redirected to file if you use “cerr” the
error doesn’t get stored in file.(This is what un-buffered means ..It cant
store the message)
 C++

#include <iostream>

using namespace std;

int main()

cerr << "An error occurred";

return 0;

Output:
An error occurred
Time Complexity: O(1)
Auxiliary Space: O(1)
147

 buffered standard error stream (clog): This is also an instance of


ostream class and used to display errors but unlike cerr the error is first
inserted into a buffer and is stored in the buffer until it is not fully filled. or
the buffer is not explicitly flushed (using flush()). The error message will
be displayed on the screen too.
 C++

#include <iostream>

using namespace std;

int main()

clog << "An error occurred";

return 0;

Output:
An error occurred
Time Complexity: O(1)
Auxiliary Space: O(1)
148

SECTION-III
INHERIATANCE AND POLYMORPHISM

Derived and Base Class:


Base Class: A base class is a class in Object-Oriented Programming
language, from which other classes are derived. The class which inherits the
base class has all members of a base class as well as can also have some
additional properties. The Base class members and member functions are
inherited to Object of the derived class. A base class is also called parent
class or superclass.
Derived Class: A class that is created from an existing class. The derived
class inherits all members and member functions of a base class. The
derived class can have more functionality with respect to the Base class and
can easily access the Base class. A Derived class is also called a child
class or subclass.
Syntax for creating Derive Class:

class BaseClass{
// members....
// member function
}

class DerivedClass : public BaseClass{


// members....
// member function
}
Difference between Base Class and Derived Class:

S.No. BASE CLASS DERIVED CLASS

1. A class from which properties are A class from which is inherited


inherited. from the base class.

2. It is also known as parent class or It is also known as child class


superclass. subclass.
149

3. It cannot inherit properties and It can inherit properties and


methods of Derived Class. methods of Base Class.

Syntax:
Syntax: class DerivedClass :
class BaseClass{ access_specifier BaseClass{
// members…. // members….
4. // member function // member function
} }

Below is the program to illustrate Base Class and Derived Class:

 CPP

// C++ program to illustrate

// Base & Derived Class

#include <iostream>

using namespace std;

// Declare Base Class

class Base {

public:

int a;

};

// Declare Derived Class


150

class Derived : public Base {

public:

int b;

};

// Driver Code

int main()

// Initialise a Derived class geeks

Derived geeks;

// Assign value to Derived class variable

geeks.b = 3;

// Assign value to Base class variable

// via derived class

geeks.a = 4;

cout << "Value from derived class: "

<< geeks.b << endl;


151

cout << "Value from base class: "

<< geeks.a << endl;

return 0;

Output:
Value from derived class: 3
Value from base class: 4

Different Types of Inheritance:


In C++, inheritance is a process in which one object acquires all the properties and
behaviors of its parent object automatically. In such way, you can reuse, extend or
modify the attributes and behaviors which are defined in other class.

In C++, the class which inherits the members of another class is called derived class
and the class whose members are inherited is called base class. The derived class is the
specialized class for the base class.

Advantage of C++ Inheritance


Code reusability: Now you can reuse the members of your parent class. So, there is
no need to define the member again. So less code is required in the class.

Types Of Inheritance
C++ supports five types of inheritance:

o Single inheritance
o Multiple inheritance
o Hierarchical inheritance
o Multilevel inheritance
152

o Hybrid inheritance

Derived Classes
A Derived class is defined as the class derived from the base class.

The Syntax of Derived class:

1. class derived_class_name :: visibility-mode base_class_name


2. {
3. // body of the derived class.
4. }

Where,

derived_class_name: It is the name of the derived class.

visibility mode: The visibility mode specifies whether the features of the base class
are publicly inherited or privately inherited. It can be public or private.

base_class_name: It is the name of the base class.

o When the base class is privately inherited by the derived class, public members of the
base class becomes the private members of the derived class. Therefore, the public
members of the base class are not accessible by the objects of the derived class only
by the member functions of the derived class.
153

o When the base class is publicly inherited by the derived class, public members of the
base class also become the public members of the derived class. Therefore, the public
members of the base class are accessible by the objects of the derived class as well as
by the member functions of the base class.

Note:
o In C++, the default mode of visibility is private.
o The private members of the base class are never inherited.

C++ Single Inheritance


Single inheritance is defined as the inheritance in which a derived class is inherited
from the only one base class.

Where 'A' is the base class, and 'B' is the derived class.

C++ Single Level Inheritance Example: Inheriting


Fields
When one class inherits another class, it is known as single level inheritance. Let's see
the example of single level inheritance which inherits the fields only.

1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. float salary = 60000;
6. };
7. class Programmer: public Account {
8. public:
9. float bonus = 5000;
154

10. };
11. int main(void) {
12. Programmer p1;
13. cout<<"Salary: "<<p1.salary<<endl;
14. cout<<"Bonus: "<<p1.bonus<<endl;
15. return 0;
16. }

Output:

Salary: 60000
Bonus: 5000

In the above example, Employee is the base class and Programmer is


the derived class.

C++ Single Level Inheritance Example: Inheriting


Methods
Let's see another example of inheritance in C++ which inherits methods only.

1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat() {
6. cout<<"Eating..."<<endl;
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void bark(){
13. cout<<"Barking...";
14. }
15. };
16. int main(void) {
17. Dog d1;
18. d1.eat();
155

19. d1.bark();
20. return 0;
21. }

Output:

Eating...
Barking...

Let's see a simple example.

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. int a = 4;
6. int b = 5;
7. public:
8. int mul()
9. {
10. int c = a*b;
11. return c;
12. }
13. };
14.
15. class B : private A
16. {
17. public:
18. void display()
19. {
20. int result = mul();
21. std::cout <<"Multiplication of a and b is : "<<result<< std::endl;
22. }
23. };
24. int main()
25. {
26. B b;
27. b.display();
28.
156

29. return 0;
30. }

Output:

Multiplication of a and b is : 20

In the above example, class A is privately inherited. Therefore, the mul() function of
class 'A' cannot be accessed by the object of class B. It can only be accessed by the
member function of class B.

How to make a Private Member Inheritable


The private member is not inheritable. If we modify the visibility mode by making it
public, but this takes away the advantage of data hiding.

C++ introduces a third visibility modifier, i.e., protected. The member which is
declared as protected will be accessible to all the member functions within the class as
well as the class immediately derived from it.

Visibility modes can be classified into three categories:

o Public: When the member is declared as public, it is accessible to all the functions of
the program.
o Private: When the member is declared as private, it is accessible within the class only.
o Protected: When the member is declared as protected, it is accessible within its own
class as well as the class immediately derived from it.

Visibility of Inherited Members

Base class visibility Derived class visibility


157

Public Private Pro

Private Not Inherited Not Inherited Not

Protected Protected Private Prot

Public Public Private Prot

C++ Multilevel Inheritance


Multilevel inheritance is a process of deriving a class from another derived class.

C++ Multi Level Inheritance Example


When one class inherits another class which is further inherited by another class, it is
known as multi level inheritance in C++. Inheritance is transitive so the last derived
class acquires all the members of all its base classes.

Let's see the example of multi level inheritance in C++.

1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat() {
158

6. cout<<"Eating..."<<endl;
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void bark(){
13. cout<<"Barking..."<<endl;
14. }
15. };
16. class BabyDog: public Dog
17. {
18. public:
19. void weep() {
20. cout<<"Weeping...";
21. }
22. };
23. int main(void) {
24. BabyDog d1;
25. d1.eat();
26. d1.bark();
27. d1.weep();
28. return 0;
29. }

Output:

Eating...
Barking...
Weeping...

C++ Multiple Inheritance


Multiple inheritance is the process of deriving a new class that inherits the attributes
from two or more classes.
159

Syntax of the Derived class:

1. class D : visibility B-1, visibility B-2, ?


2. {
3. // Body of the class;
4. }

Let's see a simple example of multiple inheritance.

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. protected:
6. int a;
7. public:
8. void get_a(int n)
9. {
10. a = n;
11. }
12. };
13.
14. class B
15. {
16. protected:
17. int b;
18. public:
19. void get_b(int n)
20. {
21. b = n;
160

22. }
23. };
24. class C : public A,public B
25. {
26. public:
27. void display()
28. {
29. std::cout << "The value of a is : " <<a<< std::endl;
30. std::cout << "The value of b is : " <<b<< std::endl;
31. cout<<"Addition of a and b is : "<<a+b;
32. }
33. };
34. int main()
35. {
36. C c;
37. c.get_a(10);
38. c.get_b(20);
39. c.display();
40.
41. return 0;
42. }

Output:

The value of a is : 10
The value of b is : 20
Addition of a and b is : 30

In the above example, class 'C' inherits two base classes 'A' and 'B' in a public mode.

Ambiquity Resolution in Inheritance


Ambiguity can be occurred in using the multiple inheritance when a function with the
same name occurs in more than one base class.

Let's understand this through an example:

1. #include <iostream>
2. using namespace std;
3. class A
161

4. {
5. public:
6. void display()
7. {
8. std::cout << "Class A" << std::endl;
9. }
10. };
11. class B
12. {
13. public:
14. void display()
15. {
16. std::cout << "Class B" << std::endl;
17. }
18. };
19. class C : public A, public B
20. {
21. void view()
22. {
23. display();
24. }
25. };
26. int main()
27. {
28. C c;
29. c.display();
30. return 0;
31. }

Output:

error: reference to 'display' is ambiguous


display();

o The above issue can be resolved by using the class resolution operator with the
function. In the above example, the derived class code can be rewritten as:

1. class C : public A, public B


2. {
162

3. void view()
4. {
5. A :: display(); // Calling the display() function of class A.
6. B :: display(); // Calling the display() function of class B.
7.
8. }
9. };

An ambiguity can also occur in single inheritance.

Consider the following situation:

1. class A
2. {
3. public:
4. void display()
5. {
6. cout<<?Class A?;
7. }
8. } ;
9. class B
10. {
11. public:
12. void display()
13. {
14. cout<<?Class B?;
15. }
16. } ;

In the above case, the function of the derived class overrides the method of the base
class. Therefore, call to the display() function will simply call the function defined in the
derived class. If we want to invoke the base class function, we can use the class
resolution operator.

1. int main()
2. {
3. B b;
4. b.display(); // Calling the display() function of B class.
5. b.B :: display(); // Calling the display() function defined in B class.
163

6. }

C++ Hybrid Inheritance


Hybrid inheritance is a combination of more than one type of inheritance.

Let's see a simple example:

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. protected:
6. int a;
7. public:
8. void get_a()
9. {
10. std::cout << "Enter the value of 'a' : " << std::endl;
11. cin>>a;
12. }
13. };
14.
15. class B : public A
16. {
17. protected:
18. int b;
164

19. public:
20. void get_b()
21. {
22. std::cout << "Enter the value of 'b' : " << std::endl;
23. cin>>b;
24. }
25. };
26. class C
27. {
28. protected:
29. int c;
30. public:
31. void get_c()
32. {
33. std::cout << "Enter the value of c is : " << std::endl;
34. cin>>c;
35. }
36. };
37.
38. class D : public B, public C
39. {
40. protected:
41. int d;
42. public:
43. void mul()
44. {
45. get_a();
46. get_b();
47. get_c();
48. std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;
49. }
50. };
51. int main()
52. {
53. D d;
54. d.mul();
55. return 0;
165

56. }

Output:

Enter the value of 'a' :


10
Enter the value of 'b' :
20
Enter the value of c is :
30
Multiplication of a,b,c is : 6000

C++ Hierarchical Inheritance


Hierarchical inheritance is defined as the process of deriving more than one class from
a base class.

Syntax of Hierarchical inheritance:

1. class A
2. {
3. // body of the class A.
4. }
5. class B : public A
6. {
7. // body of class B.
8. }
9. class C : public A
10. {
11. // body of class C.
12. }
13. class D : public A
14. {
15. // body of class D.
166

16. }

Let's see a simple example:

1. #include <iostream>
2. using namespace std;
3. class Shape // Declaration of base class.
4. {
5. public:
6. int a;
7. int b;
8. void get_data(int n,int m)
9. {
10. a= n;
11. b = m;
12. }
13. };
14. class Rectangle : public Shape // inheriting Shape class
15. {
16. public:
17. int rect_area()
18. {
19. int result = a*b;
20. return result;
21. }
22. };
23. class Triangle : public Shape // inheriting Shape class
24. {
25. public:
26. int triangle_area()
27. {
28. float result = 0.5*a*b;
29. return result;
30. }
31. };
32. int main()
33. {
167

34. Rectangle r;
35. Triangle t;
36. int length,breadth,base,height;
37. std::cout << "Enter the length and breadth of a rectangle: " << std::endl;
38. cin>>length>>breadth;
39. r.get_data(length,breadth);
40. int m = r.rect_area();
41. std::cout << "Area of the rectangle is : " <<m<< std::endl;
42. std::cout << "Enter the base and height of the triangle: " << std::endl;
43. cin>>base>>height;
44. t.get_data(base,height);
45. float n = t.triangle_area();
46. std::cout <<"Area of the triangle is : " << n<<std::endl;
47. return 0;
48. }

Output:

Enter the length and breadth of a rectangle:


23
20
Area of the rectangle is : 460
Enter the base and height of the triangle:
2
5
Area of the triangle is : 5

Overriding Member Function:


If derived class defines same function as defined in its base class, it is known as function
overriding in C++. It is used to achieve runtime polymorphism. It enables you to
provide specific implementation of the function which is already provided by its base
class.

C++ Function Overriding Example


Let's see a simple example of Function overriding in C++. In this example, we are
overriding the eat() function.

1. #include <iostream>
2. using namespace std;
168

3. class Animal {
4. public:
5. void eat(){
6. cout<<"Eating...";
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void eat()
13. {
14. cout<<"Eating bread...";
15. }
16. };
17. int main(void) {
18. Dog d = Dog();
19. d.eat();
20. return 0;
21. }

Output:

Eating bread...

Abstract Class:
By definition, a C++ abstract class must include at least one pure virtual function.
Alternatively, put a function without a definition. Because the subclass would otherwise
turn into an abstract class in and of itself, the abstract class's descendants must specify
the pure virtual function.

Broad notions are expressed using abstract classes, which can then be utilized to
construct more specific classes. You cannot make an object of the abstract class type.
However, pointers and references can be used to abstract class types. When
developing an abstract class, define at least one pure virtual feature. A virtual function
is declared using the pure specifier (= 0) syntax.
169

Consider the example of the virtual function. Although the class's objective is to
provide basic functionality for shapes, elements of type shapes are far too general to
be of much value. Because of this, the shape is a good candidate for an abstract class:

Code
1. C-lass classname //abstract class
2. {
3. //data members
4. public:
5. //pure virtual function
6. /* Other members */
7. };

What are the characteristics of abstract class?


Although the Abstract class type cannot be created from scratch, it can have pointers
and references made to it. A pure virtual function can exist in an abstract class in
addition to regular functions and variables. Upcasting, which lets derived classes access
their interface, is the main usage of abstract classes. Classes that descended from an
abstract class must implement all pure virtues.

What are the restrictions to abstract class?


The following uses of abstract classes are not permitted:

1. Conversions made consciously


2. Member data or variables
3. Types of function output
4. Forms of debate

It is unknown what happens when a pure virtual method is called explicitly or indirectly
by the native code function Object () of an abstract class. Conversely, abstract group
constructors and destructors can call additional member functions.

Although the constructors of the abstract class are allowed to call other member
functions, if they either directly or indirectly call a pure virtual function, the outcome is
unknown. But hold on! What exactly is a pure virtual function?

Let's first examine virtual functions in order to comprehend the pure virtual function.
170

A member function that has been redefined by a derived class from a base class
declaration is referred to as a virtual function.

A virtual function that lacks definition or logic is known as an abstract function or a


pure virtual function. At the time of declaration, 0 is assigned to it.

How Important Abstraction Is in Daily Life?


The ATM machine is another example of abstraction in everyday life;. However, we all
use the ATM to do tasks like cash withdrawal, money transfers, generating mini-
statements, and so on, and we have no access to the ATM's internal data. Data
protection techniques like data abstraction can prevent unauthorized access to data.

What is the difference between abstract class and


interface?

Interface Abstract class

An interface can only inherit from With the Extended keyword, an abstract
another interface. class can enforce an interface and inherit
from another class.

Use of the implements keyword is Use the extends keyword to inherit from
required in order to implement an an abstract class.
interface.

What is an example of an abstract class?


Consider developing a calculator that will output the shape's perimeter when it is
entered. Consider the type of programming you would use to create such a calculator.
By creating distinct functions inside the Shape class, you may start with a few basic
forms and hardcode the perimeter.

This is how the class might appear:

What is an example of an abstract class?


Consider developing a calculator that will output the shape's perimeter when it is
entered. Consider the type of programming you would use to create such a calculator.
171

By creating distinct functions inside the Shape class, you may start with a few basic
forms and hardcode the perimeter.

This is how the class might appear:

1. class Shape {
2. public:
3. // All the functions of both square and rectangle are clubbed together in a single class.
4. void width(int w) {
5. shape_width = w;
6. }
7. void height(int h) {
8. shape_height = h;
9. }
10. int areaOfSquare(int s) {
11. return 4 * s;
12. }
13. int areaOfRectange(int l, int b) {
14. return (l * b);
15. }
16. protected:
17. int shape_width;
18. int shape_height;
19. };
20. int main (){
21. shapes R;
22. R.width(5);
23. R.height(10);
24. cout<<"The area of rectangle is"<<R.areaOfRectangle";
25. return 0;
26. }

Output:
172

While OOP advises that we should attempt to adhere to real-world reasoning, this will
still function. As a result, we can create the class Shape as the parent class, with the
classes Square and Rectangle acting as the children. If you want to add something new
later, you can do it in the child class, which will make the program simpler to maintain.
We must use Abstract Classes to put this feature into practice. At least one pure virtual
function is required for abstract classes in C++. In order to prevent the subclass from
becoming an abstract class, the abstract class's inheriting classes must specify the pure
virtual function.

Public and Private Inheritance:


Before learning about Inheritance Access we need to know about access
specifiers. There are three Access specifiers in C++. These are:
public – members are accessible from outside the class, and members can
be accessed from anywhere.
private – members cannot be accessed (or viewed) from outside the class,
i.e members are private to that class only.
protected – members cannot be accessed from outside the class, but, they
can be accessed in inherited classes or derived classes.

Public, Protected, and Private inheritance in C++

public, protected, and private inheritance have the following features:


 public inheritance makes public members of the base class public in the
derived class, and the protected members of the base class remain
protected in the derived class.
 protected inheritance makes the public and protected members of the
base class protected in the derived class.
 private inheritance makes the public and protected members of the base
class private in the derived class.
Accessibility Of Inheritance Access:

Inheritance Access

1. C++ public Inheritance


173

In this example, public inheritance is demonstrated. Since private and


protected members will not be directly accessed from main( ) so we have
had to create functions name getPVT( ) to access the private variable and
getProt( ) to access the protected variable from the inherited class.
Example:
 C++

// C++ program to demonstrate the working of public

// inheritance

#include <iostream>

using namespace std;

class Base {

private:

int pvt = 1;

protected:

int prot = 2;

public:

int pub = 3;

// function to access private member

int getPVT() { return pvt; }


174

};

class PublicDerived : public Base {

public:

// function to access protected member from Base

int getProt() { return prot; }

};

int main()

PublicDerived object1;

cout << "Private = " << object1.getPVT() << endl;

cout << "Protected = " << object1.getProt() << endl;

cout << "Public = " << object1.pub << endl;

return 0;

Output
Private = 1
Protected = 2
Public = 3

2. C++ protected Inheritance


We know that protected members can only be accessed from the Derived
class. These members cannot be directly accessed from outside the class.
So we cannot use getPVT() from ProtectedDerived.This is also why we need
175

to create getPub() function in the Derived class in order to access the pub
variable.
Example:
 C++

// C++ program to demonstrate the working

// of protected inheritance

#include <iostream>

using namespace std;

class Base {

private:

int pvt = 1;

protected:

int prot = 2;

public:

int pub = 3;

// function to access private member

int getPVT() { return pvt; }

};
176

class ProtectedDerived : protected Base {

public:

// function to access protected member from Base

int getProt() { return prot; }

// function to access public member from Base

int getPub() { return pub; }

};

int main()

ProtectedDerived object1;

cout << "Private cannot be accessed." << endl;

cout << "Protected = " << object1.getProt() << endl;

cout << "Public = " << object1.getPub() << endl;

return 0;

Output
Private cannot be accessed.
Protected = 2
Public = 3

3. C++ private Inheritance


177

We know that private members cannot be accessed from the Derived class.
These members cannot be directly accessed from outside the class. So we
cannot use getPVT() from PrivateDerived. So we need to create the getPub()
function in PrivateDerived in order to access the pub variable.
Example:
 C++

// C++ program to demonstrate the working

// of private inheritance

#include <iostream>

using namespace std;

class Base {

private:

int pvt = 1;

protected:

int prot = 2;

public:

int pub = 3;

// function to access private member

int getPVT() { return pvt; }


178

};

class PrivateDerived : private Base {

public:

// function to access protected member from Base

int getProt() { return prot; }

// function to access private member

int getPub() { return pub; }

};

int main()

PrivateDerived object1;

cout << "Private cannot be accessed." << endl;

cout << "Protected = " << object1.getProt() << endl;

cout << "Public = " << object1.getPub() << endl;

return 0;

Output
Private cannot be accessed.
Protected = 2
Public = 3
179

Ambiguity in Multiple Inheritance:


Multiple Inheritance is the concept of the Inheritance in C++ that allows a child class
to inherit properties or behaviour from multiple base classes. Therefore, we can say it
is the process that enables a derived class to acquire member functions, properties,
characteristics from more than one base class.

Diagram of the Multiple Inheritance


Following is the diagram of the Multiple Inheritances in the C++ programming
language.

In the above diagram, there are two-parent classes: Base Class 1 and Base Class 2,
whereas there is only one Child Class. The Child Class acquires all features from both
Base class 1 and Base class 2. Therefore, we termed the type of Inheritance as Multiple
Inheritance.

Syntax of the Multiple Inheritance


1. class A
2. {
3. // code of class A
4. }
5. class B
6. {
7. // code of class B
8. }
9. class C: public A, public B (access modifier class_name)
180

10. {
11. // code of the derived class
12. }

In the above syntax, class A and class B are two base classes, and class C is the child
class that inherits some features of the parent classes.

Let's write the various program of Multiple Inheritance to inherit the member functions
and functionality from more than one base class using the derived class.

Example 1: Program to use the Multiple Inheritance


Program1.cpp

1. #include <iostream>
2. using namespace std;
3.
4. // create a base class1
5. class Base_class
6. {
7. // access specifier
8. public:
9. // It is a member function
10. void display()
11. {
12. cout << " It is the first function of the Base class " << endl;
13. }
14. };
15.
16. // create a base class2
17. class Base_class2
18. {
19. // access specifier
20. public:
21. // It is a member function
22. void display2()
23. {
24. cout << " It is the second function of the Base class " << endl;
25. }
181

26. };
27.
28. /* create a child_class to inherit features of Base_class and Base_class2 with access specifier. *
/
29. class child_class: public Base_class, public Base_class2
30. {
31.
32. // access specifier
33. public:
34. void display3() // It is a member function of derive class
35. {
36. cout << " It is the function of the derived class " << endl;
37. }
38.
39. };
40.
41. int main ()
42. {
43. // create an object for derived class
44. child_class ch;
45. ch.display(); // call member function of Base_class1
46. ch.display2(); // call member function of Base_class2
47. ch.display3(); // call member function of child_class
48. }

Output

It is the first function of the Base class


It is the second function of the Base class
It is the function of the derived class

In the above program, we created two base classes and one child class.
The child_class invoke member function display() and display2() from both parent
classes Base_class and Base_class2 with the help of child class's object ch.

Example 2: Use Multiple Inheritance to perform the


arithmetic operation
Let's create a derived class to inherit the member functions from multiple base classes
in C++ programming.
182

Program2.cpp

1. #include <iostream>
2. using namespace std;
3.
4. // create add class
5. class add
6. {
7. public:
8. int x = 20;
9. int y = 30;
10. void sum()
11. {
12. cout << " The sum of " << x << " and " << y << " is " <<x+y << endl;
13. }
14. };
15.
16. // create Mul class
17. class Mul
18. {
19. public:
20. int a = 20;
21. int b = 30;
22. void mul()
23. {
24. cout << " The Multiplication of " << a << " and " << b << " is " <<a*b << endl;
25. }
26. };
27.
28. // create Subclass
29. class Sub
30. {
31. public:
32. int a = 50;
33. int b = 30;
34. void sub()
35. {
183

36. cout << " The Subtraction of " << a << " and " << b << " is " <<a-b << endl;
37. }
38. };
39.
40. // create Div class
41. class Div
42. {
43. // access specifier
44. public:
45. int a = 150;
46. int b = 30;
47. void div()
48. {
49. cout << " The Division of " << a << " and " << b << " is " <<a/b << endl;
50. }
51. };
52.
53. // create a derived class to derive the member functions of all base classes
54. class derived: public add, public Div, public Sub, public Mul
55. {
56. // access specifier
57. public:
58. int p = 12;
59. int q = 5;
60. void mod()
61. {
62. cout << "The Modulus of " << p << " and " <<q << " is " << p % q << endl;
63. }
64. };
65.
66. int main ()
67. {
68. // create an object of the derived class
69. derived dr;
70. dr.mod(); // call derive class member function
71. // call all member function of class add, Div, Sub and Mul
72. dr.sum();
184

73. dr.mul();
74. dr.div();
75. dr.sub();
76. }

Output

The Modulus of 12 and 5 is 2


The sum of 20 and 30 is 50
The Multiplication of 20 and 30 is 600
The Division of 150 and 30 is 5
The Subtraction of 50 and 30 is 20
Example 3: Get the average marks of six subjects using the
Multiple Inheritance
Let's create another program to print the average marks of six subjects using the
multiple Inheritance in the C++ programming language.

Program3.cpp

1. #include <iostream>
2. using namespace std;
3.
4. // create base class1
5. class student_detail
6. {
7. // access specifier
8. protected:
9. int rno, sum = 0, i, marks[5];
10.
11. // access specifier
12. public:
13. void detail()
14. {
15.
16.
17. cout << " Enter the Roll No: " << endl;
18. cin >> rno;
19.
20. cout << " Enter the marks of five subjects " << endl;
185

21. // use for loop


22. for (i = 0; i < 5; i++)
23. {
24. cin >> marks[i];
25. }
26.
27.
28. for ( i = 0; i < 5; i++)
29. {
30. // store the sum of five subject
31. sum = sum + marks[i];
32. }
33. }
34.
35. };
36.
37. // create base class2
38. class sports_mark
39. {
40. protected:
41. int s_mark;
42.
43. public:
44.
45. void get_mark()
46. {
47. cout << "\n Enter the sports mark: ";
48. cin >> s_mark;
49. }
50. };
51.
52. /* create a result as the child class to inherit functions of the parent class: student_detail and
sports_mark.*/
53. class result: public student_detail, public sports_mark
54. {
55. int tot, avg;
56. public:
186

57.
58. // create member function of child class
59. void disp ()
60. {
61. tot = sum + s_mark;
62. avg = tot / 6; // total marks of six subject / 6
63. cout << " \n \n \t Roll No: " << rno << " \n \t Total: " << tot << endl;
64. cout << " \n \t Average Marks: " << avg;
65. }
66. };
67.
68. int main ()
69. {
70. result obj; // create an object of the derived class
71.
72. // call the member function of the base class
73. obj.detail();
74. obj.get_mark();
75. obj.disp();
76. }

Output

Enter the Roll No:


25
Enter the marks of five subjects
90
85
98
80
75

Enter the sports mark: 99

Roll No: 25
Total: 527

Average Marks: 87
Ambiguity Problem in Multiple Inheritance
In Multiple Inheritance, when a single class is derived from two or more base or parent
classes. So, it might be possible that both the parent class have the same-named
member functions, and it shows ambiguity when the child class object invokes one of
187

the same-named member functions. Hence, we can say, the C++ compiler is confused
in selecting the member function of a class for the execution of a program.

Program to demonstrate the Ambiguity Problem in Multiple


Inheritance
Let's write a simple to invoke the same member function of the parent class using
derived class in C++ programming.

Program4.cpp

1. #include <iostream>
2. #include <conio.h>
3.
4. using namespace std;
5.
6. // create class A
7. class A
8. {
9. public:
10. void show()
11. {
12. cout << " It is the member function of class A " << endl;
13. }
14. };
15.
16. // create class B
17. class B
18. {
19. public:
20. void show()
21. {
22. cout << " It is the member function of class B " << endl;
23. }
24. };
25.
26.
27. // create a child class to inherit the member function of class A and class B
28. class child: public A, public B
188

29. {
30. public:
31. void disp()
32. {
33. cout << " It is the member function of the child class " << endl;
34. }
35. };
36.
37. int main ()
38. {
39. // create an object of the child class to access the member function
40. child ch;
41. ch.show(); // It causes ambiguity
42. ch.disp();
43. return 0;
44. }

When the above program is compiled, it throws the show() member function is
ambiguous. Because of both the base class A and B, defining the same member
function show(), and when the derived class's object call the shows() function, it shows
ambiguity in multiple inheritances.

Therefore, we need to resolve the ambiguous problem in multiple Inheritance. The


ambiguity problem can be resolved by defining the class name and scope resolution
(::) operator to specify the class from which the member function is invoked in the
child class.

Syntax of the Ambiguity Resolution

1. Derived_obj_name.parent_class_name : : same_named_memberFunction ( [parameter] );

For example,

1. ch.A:: show(); // class_name and scope resolution operator with member function
2. ch.B::show();

After making some changes, now we again execute the above program that returns
the given below Output.

1. It is the member function of the child class


2. It is the member function of class A
189

3. It is the member function of class B

Virtual Function:

o A C++ virtual function is a member function in the base class that you redefine
in a derived class. It is declared using the virtual keyword.
o It is used to tell the compiler to perform dynamic linkage or late binding on the
function.
o There is a necessity to use the single pointer to refer to all the objects of the
different classes. So, we create the pointer to the base class that refers to all the
derived objects. But, when base class pointer contains the address of the
derived class object, always executes the base class function. This issue can only
be resolved by using the 'virtual' function.
o A 'virtual' is a keyword preceding the normal declaration of a function.
o When the function is made virtual, C++ determines which function is to be
invoked at the runtime based on the type of the object pointed by the base
class pointer.

Late binding or Dynamic linkage


In late binding function call is resolved during runtime. Therefore compiler determines
the type of object at runtime, and then binds the function call.

Rules of Virtual Function

o Virtual functions must be members of some class.


o Virtual functions cannot be static members.
o They are accessed through object pointers.
o They can be a friend of another class.
o A virtual function must be defined in the base class, even though it is not used.
o The prototypes of a virtual function of the base class and all the derived classes
must be identical. If the two functions with the same name but different
prototypes, C++ will consider them as the overloaded functions.
o We cannot have a virtual constructor, but we can have a virtual destructor
190

o Consider the situation when we don't use the virtual keyword.

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. int x=5;
6. public:
7. void display()
8. {
9. std::cout << "Value of x is : " << x<<std::endl;
10. }
11. };
12. class B: public A
13. {
14. int y = 10;
15. public:
16. void display()
17. {
18. std::cout << "Value of y is : " <<y<< std::endl;
19. }
20. };
21. int main()
22. {
23. A *a;
24. B b;
25. a = &b;
26. a->display();
27. return 0;
28. }

Output:

Value of x is : 5

In the above example, * a is the base class pointer. The pointer can only access the
base class members but not the members of the derived class. Although C++ permits
the base pointer to point to any object derived from the base class, it cannot directly
191

access the members of the derived class. Therefore, there is a need for virtual function
which allows the base pointer to access the members of the derived class.

C++ virtual function Example


Let's see the simple example of C++ virtual function used to invoked the derived class
in a program.

1. #include <iostream>
2. {
3. public:
4. virtual void display()
5. {
6. cout << "Base class is invoked"<<endl;
7. }
8. };
9. class B:public A
10. {
11. public:
12. void display()
13. {
14. cout << "Derived Class is invoked"<<endl;
15. }
16. };
17. int main()
18. {
19. A* a; //pointer of base class
20. B b; //object of derived class
21. a = &b;
22. a->display(); //Late Binding occurs
23. }

Output:

Derived Class is invoked

Pure Virtual Function


192

o A virtual function is not used for performing any task. It only serves as a
placeholder.
o When the function has no definition, such function is known as "do-nothing"
function.
o The "do-nothing" function is known as a pure virtual function. A pure virtual
function is a function declared in the base class that has no definition relative
to the base class.
o A class containing the pure virtual function cannot be used to declare the
objects of its own, such classes are known as abstract base classes.
o The main objective of the base class is to provide the traits to the derived classes
and to create the base pointer used for achieving the runtime polymorphism.

Pure virtual function can be defined as:

1. virtual void display() = 0;

Let's see a simple example:

1. #include <iostream>
2. using namespace std;
3. class Base
4. {
5. public:
6. virtual void show() = 0;
7. };
8. class Derived : public Base
9. {
10. public:
11. void show()
12. {
13. std::cout << "Derived class is derived from the base class." << std::endl;
14. }
15. };
16. int main()
17. {
18. Base *bptr;
19. //Base b;
193

20. Derived d;
21. bptr = &d;
22. bptr->show();
23. return 0;
24. }

Output:

Derived class is derived from the base class.

In the above example, the base class contains the pure virtual function. Therefore, the
base class is an abstract base class. We cannot create the object of the base class.

Friend Function:
If a function is defined as a friend function in C++, then the protected and private data
of a class can be accessed using the function.

By using the keyword friend compiler knows the given function is a friend function.

For accessing the data, the declaration of a friend function should be done inside the
body of a class starting with the keyword friend.

Declaration of friend function in C++


1. class class_name
2. {
3. friend data_type function_name(argument/s); // syntax of friend function.
4. };

In the above declaration, the friend function is preceded by the keyword friend. The
function can be defined anywhere in the program like a normal C++ function. The
function definition does not use either the keyword friend or scope resolution
operator.

Characteristics of a Friend function:

o The function is not in the scope of the class to which it has been declared as a friend.
o It cannot be called using the object as it is not in the scope of that class.
o It can be invoked like a normal function without using the object.
194

o It cannot access the member names directly and has to use an object name and dot
membership operator with the member name.
o It can be declared either in the private or the public part.

C++ friend function Example


Let's see the simple example of C++ friend function used to print the length of a box.

1. #include <iostream>
2. using namespace std;
3. class Box
4. {
5. private:
6. int length;
7. public:
8. Box(): length(0) { }
9. friend int printLength(Box); //friend function
10. };
11. int printLength(Box b)
12. {
13. b.length += 10;
14. return b.length;
15. }
16. int main()
17. {
18. Box b;
19. cout<<"Length of box: "<< printLength(b)<<endl;
20. return 0;
21. }

Output:

Length of box: 10

Let's see a simple example when the function is friendly to two classes.

1. #include <iostream>
2. using namespace std;
3. class B; // forward declarartion.
195

4. class A
5. {
6. int x;
7. public:
8. void setdata(int i)
9. {
10. x=i;
11. }
12. friend void min(A,B); // friend function.
13. };
14. class B
15. {
16. int y;
17. public:
18. void setdata(int i)
19. {
20. y=i;
21. }
22. friend void min(A,B); // friend function
23. };
24. void min(A a,B b)
25. {
26. if(a.x<=b.y)
27. std::cout << a.x << std::endl;
28. else
29. std::cout << b.y << std::endl;
30. }
31. int main()
32. {
33. A a;
34. B b;
35. a.setdata(10);
36. b.setdata(20);
37. min(a,b);
38. return 0;
39. }
196

Output:

10

In the above example, min() function is friendly to two classes, i.e., the min() function
can access the private members of both the classes A and B.

C++ Friend class


A friend class can access both private and protected members of the class in which it
has been declared as friend.

Let's see a simple example of a friend class.

1. #include <iostream>
2.
3. using namespace std;
4.
5. class A
6. {
7. int x =5;
8. friend class B; // friend class.
9. };
10. class B
11. {
12. public:
13. void display(A &a)
14. {
15. cout<<"value of x is : "<<a.x;
16. }
17. };
18. int main()
19. {
20. A a;
21. B b;
22. b.display(a);
23. return 0;
24. }

Output:
197

value of x is : 5

In the above example, class B is declared as a friend inside the class A. Therefore, B is
a friend of class A. Class B can access the private members of class A.

Static Function:
The static is a keyword in the C and C++ programming language. We use the static
keyword to define the static data member or static member function inside and outside
of the class. Let's understand the static data member and static member function using
the programs.

Static data member


When we define the data member of a class using the static keyword, the data
members are called the static data member. A static data member is similar to the
static member function because the static data can only be accessed using the static
data member or static member function. And, all the objects of the class share the
same copy of the static member to access the static data.

Syntax

1. static data_type data_member;

Here, the static is a keyword of the predefined library.

The data_type is the variable type in C++, such as int, float, string, etc.

The data_member is the name of the static data.


198

Example 1: Let's create a simple program to access the static data members in the
C++ programming language.

1. #include <iostream>
2. #include <string.h>
3. using namespace std;
4. // create class of the Car
5. class Car
6. {
7. private:
8. int car_id;
9. char car_name[20];
10. int marks;
11.
12. public:
13. // declare a static data member
14. static int static_member;
15.
16. Car()
17. {
18. static_member++;
19. }
20.
21. void inp()
22. {
23. cout << " \n\n Enter the Id of the Car: " << endl;
24. cin >> car_id; // input the id
25. cout << " Enter the name of the Car: " << endl;
26. cin >> car_name;
27. cout << " Number of the Marks (1 - 10): " << endl;
28. cin >> marks;
29. }
30.
31. // display the entered details
32. void disp ()
33. {
34. cout << " \n Id of the Car: " << car_id;
199

35. cout << "\n Name of the Car: " << car_name;
36. cout << " \n Marks: " << marks;
37.
38. }
39. };
40.
41. // initialized the static data member to 0
42. int Car::static_member = 0;
43.
44. int main ()
45. {
46. // create object for the class Car
47. Car c1;
48. // call inp() function to insert values
49. c1. inp ();
50. c1. disp();
51.
52. //create another object
53. Car c2;
54. // call inp() function to insert values
55. c2. inp ();
56. c2. disp();
57.
58.
59. cout << " \n No. of objects created in the class: " << Car :: static_member <<endl;
60. return 0;
61. }

Output

Enter the Id of the Car:


101
Enter the name of the Car:
Ferrari
Number of the Marks (1 - 10):
10

Id of the Car: 101


Name of the Car: Ferrari
Marks: 10

Enter the Id of the Car:


205
200

Enter the name of the Car:


Mercedes
Number of the Marks (1 - 10):
9

Id of the Car: 205


Name of the Car: Mercedes
Marks: 9
No. of objects created in the class: 2
Static Member Functions
The static member functions are special functions used to access the static data
members or other static member functions. A member function is defined using the
static keyword. A static member function shares the single copy of the member
function to any number of the class' objects. We can access the static member function
using the class name or class' objects. If the static member function accesses any non-
static data member or non-static member function, it throws an error.

Syntax

1. class_name::function_name (parameter);

Here, the class_name is the name of the class.

function_name: The function name is the name of the static member function.

parameter: It defines the name of the pass arguments to the static member function.

Example 2: Let's create another program to access the static member function using
the class name in the C++ programming language.

1. #include <iostream>
2. using namespace std;
3. class Note
4. {
5. // declare a static data member
6. static int num;
7.
8. public:
9. // create static member function
10. static int func ()
11. {
12. return num;
13. }
201

14. };
15. // initialize the static data member using the class name and the scope resolution operator
16. int Note :: num = 5;
17.
18. int main ()
19. {
20. // access static member function using the class name and the scope resolution
21. cout << " The value of the num is: " << Note:: func () << endl;
22. return 0;
23. }

Output

The value of the num is: 5

Example 3: Let's create another program to access the static member function using
the class' object in the C++ programming language.

1. #include <iostream>
2. using namespace std;
3. class Note
4. {
5. // declare a static data member
6. static int num;
7.
8. public:
9. // create static member function
10. static int func ()
11. {
12. cout << " The value of the num is: " << num << endl;
13. }
14. };
15. // initialize the static data member using the class name and the scope resolution operator
16. int Note :: num = 15;
17.
18. int main ()
19. {
20. // create an object of the class Note
21. Note n;
202

22. // access static member function using the object


23. n.func();
24.
25. return 0;
26. }

Output

The value of the num is: 15

Example 4: Let's consider an example to access the static member function using the
object and class in the C++ programming language.

1. #include <iostream>
2. using namespace std;
3. class Member
4. {
5.
6. private:
7. // declaration of the static data members
8. static int A;
9. static int B;
10. static int C;
11.
12. // declare public access specifier
13. public:
14. // define the static member function
15. static void disp ()
16. {
17. cout << " The value of the A is: " << A << endl;
18. cout << " The value of the B is: " << B << endl;
19. cout << " The value of the C is: " << C << endl;
20. }
21. };
22. // initialization of the static data members
23. int Member :: A = 20;
24. int Member :: B = 30;
25. int Member :: C = 40;
26.
203

27. int main ()


28. {
29. // create object of the class Member
30. Member mb;
31. // access the static member function using the class object name
32. cout << " Print the static member through object name: " << endl;
33. mb. disp();
34. // access the static member function using the class name
35. cout << " Print the static member through the class name: " << endl;
36. Member::disp();
37. return 0;
38. }

Output

Print the static member through object name:


The value of the A is: 20
The value of the B is: 30
The value of the C is: 40
Print the static member through the class name:
The value of the A is: 20
The value of the B is: 30
The value of the C is: 40
204

SECTION-IV

EXCEPTION HANDLING

Exception and Derived Class:


Catching Base and Derived Classes as Exceptions in C++ and Java, let us understand
what exceptions and exception handling are. Exceptions are the errors which occur
while we are programming and are generally treated as unwanted errors or to
understand better. They are like the hurdles caused while programming, and exception
handling is the error handling mechanism to treat the exceptions or the limitations
that occur.

Various methods to handle exception handling and base and derived class catch as
part of exception in both C++ and Java programming languages.

o In a scenario where the base and the derived classes we have declared are caught in
the mechanism as exceptions, then we must see at the display output terminal that the
catch block of the said derived class appears before the type of base we declared.
o The above statement is valid, and we can even recheck if we put our base class before
the derived class, then the derived class which we have declared will never be reached.

Algorithm (Catching Base and Derived Classes as


Exceptions in C++ and Java)
Example:

1. begin //code starts from here


2. declare a class b.
3. say another class d which inherits class b.
4. now display an object of class d.
5. Try: throw derived.
6. Catch (d derived)
7. Print "code has been caught in the derived exception".
8. Catch (B b)
9. Print "code has been caught in the base exception".
10. End

C++ Code
205

1. //here, we are writing down the C++ programming language code to


2. //demonstrate the concept of Catching Base and
3. //Derived Classes as Exceptions in both C++ and Java languages
4. #include <iostream>
5. using namespace std;
6. class base_ {
7. };
8. class derived_: public base_ {
9. };
10. int main()
11. {
12. derived_ d;
13. //these are some necessary functionalities we may use
14. try {
15. //this is the monitored code we use
16. throw d;
17. }
18. catch (base_ b) {
19. cout << "OH! Caught Based Exception occured";
20. }
21. catch (derived_ d) {
22. //note: the catch block we wrote below will never get executed!
23. cout << "oh! caught in the derived exception...";
24. }
25. getchar();
26. return 0;
27. }

Output:

prog.cpp: In function 'int main()':


prog.cpp:20:5: warning: exception of type 'derived_' will be caught
catch (derived_ d) {
^
prog.cpp:17:5: warning: by the earlier handler for 'base_.'
catch (base_ b) {
/ tm p /vLt kM pH G zo.o
OH! Caught Based Exception occurred

C++ code
206

1. //here, we are writing down the C++ programming language code to


2. //demonstrate the concept of Catching Base and
3. //Derived Classes as Exceptions in both C++ and Java languages
4. #include <iostream>
5. using namespace std;
6.
7. class base_ {};
8. class derived : public base_ {};
9. int main()
10. {
11. derived d;
12. //these are some necessary functionalities we may use
13. try {
14.
15. //this is the monitored code we use
16. throw d;
17. }
18. catch (derived d) {
19. cout << "the code has been caught in the derived exception";
20. }
21. catch (base_ b) {
22. cout << "the code has been caught in the base exception";
23. }
24. //this below code snippet is to read out the next possible character
25. getchar();
26. return 0;
27. }

Output:

/tmp /vL tk MpH Gzo.o


the code has been caught in the derived exception

Java Code

1. //here, we are writing down the Java programming language code to


2. //demonstrate the concept of Catching Base and
3. //Derived Classes as Exceptions in both C++ and Java languages
4. class base_ extends Exception {
207

5. }
6. class derived_ extends base_ {
7. }
8. public class Main{
9. public static void main(String args[])
10. {
11. try {
12. throw new derived_();
13. }
14. catch (base_ b) {
15. }
16. catch (derived_ d) {
17. }
18. }
19. }

Output:

/tmp /vL tk MpH Gzo.o


./Main.java:13: error: exception Derived has already been caught
catch (Derived d) {
^
1 error

Java Code

1. //here, we are writing down the Java programming language code to


2. //demonstrate the concept of Catching Base and
3. //Derived Classes as Exceptions in both C++ and Java languages
4. class base_b extends Exception {}
5. class derived_d extends base_b {}
6. public class Main {
7. public static void main(String args[]) {
8. // below, we wrote the try block code snippet
9. try {
10. //this is the monitored code we use
11. throw new derived_d();
12. }
13. catch(base_b) {
14. System.out.println("the code has been caught in the base exception");
208

15. }
16. catch(derived_d) {
17. System.out.println("the code has been caught in the derived exception");
18. }
19. }
20. }

Output:

Main.java:12: error: exception Derived has already been caught


catch(derived_d) { System.out.println("the code has been caught in the
derived exception");}

Function Exception Declaration:


One of the advantages of C++ over C is Exception Handling. Exceptions are
runtime anomalies or abnormal conditions that a program encounters during
its execution. There are two types of exceptions: a)Synchronous,
b)Asynchronous (i.e., exceptions which are beyond the program’s control,
such as disc failure, keyboard interrupts etc.). C++ provides the following
specialized keywords for this purpose:
try: Represents a block of code that can throw an exception.
catch: Represents a block of code that is executed when a particular
exception is thrown.
throw: Used to throw an exception. Also used to list the exceptions that a
function throws but doesn’t handle itself.
Why Exception Handling?
The following are the main advantages of exception handling over traditional
error handling:
1) Separation of Error Handling code from Normal Code: In traditional error
handling codes, there are always if-else conditions to handle errors. These
conditions and the code to handle errors get mixed up with the normal flow.
This makes the code less readable and maintainable. With try/catch blocks,
the code for error handling becomes separate from the normal flow.
2) Functions/Methods can handle only the exceptions they choose: A
function can throw many exceptions, but may choose to handle some of
them. The other exceptions, which are thrown but not caught, can be
handled by the caller. If the caller chooses not to catch them, then the
exceptions are handled by the caller of the caller.
In C++, a function can specify the exceptions that it throws using the throw
keyword. The caller of this function must handle the exception in some way
(either by specifying it again or catching it).
3) Grouping of Error Types: In C++, both basic types and objects can be
thrown as exceptions. We can create a hierarchy of exception objects, group
209

exceptions in namespaces or classes and categorize them according to their


types.

C++ Exceptions:
When executing C++ code, different errors can occur: coding errors made by
the programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, C++ will normally stop and generate an error
message. The technical term for this is: C++ will throw an exception (error).
C++ try and catch:
Exception handling in C++ consists of three keywords: try, throw and catch:
The try statement allows you to define a block of code to be tested for errors
while it is being executed.
The throw keyword throws an exception when a problem is detected, which
lets us create a custom error.
The catch statement allows you to define a block of code to be executed if
an error occurs in the try block.
The try and catch keywords come in pairs:
We use the try block to test some code: If the value of a variable “age” is less
than 18, we will throw an exception, and handle it in our catch block.
In the catch block, we catch the error if it occurs and do something about it.
The catch statement takes a single parameter. So, if the value of age is 15
and that’s why we are throwing an exception of type int in the try block (age),
we can pass “int myNum” as the parameter to the catch statement, where
the variable “myNum” is used to output the value of age.
If no error occurs (e.g. if age is 20 instead of 15, meaning it will be greater
than 18), the catch block is skipped.
Exception Handling in C++
1) The following is a simple example to show exception handling in C++. The
output of the program explains the flow of execution of try/catch blocks.
 CPP

#include <iostream>

using namespace std;


210

int main()

int x = -1;

// Some code

cout << "Before try \n";

try {

cout << "Inside try \n";

if (x < 0)

throw x;

cout << "After throw (Never executed) \n";

catch (int x ) {

cout << "Exception Caught \n";

cout << "After catch (Will be executed) \n";

return 0;

Output:
211

Before try
Inside try
Exception Caught
After catch (Will be executed)
2) There is a special catch block called the ‘catch all’ block, written as
catch(…), that can be used to catch all types of exceptions. For example, in
the following program, an int is thrown as an exception, but there is no catch
block for int, so the catch(…) block will be executed.
 CPP

#include <iostream>

using namespace std;

int main()

try {

throw 10;

catch (char *excp) {

cout << "Caught " << excp;

catch (...) {

cout << "Default Exception\n";

return 0;
212

Output:
Default Exception
3) Implicit type conversion doesn’t happen for primitive types. For example,
in the following program, ‘a’ is not implicitly converted to int.
 CPP

#include <iostream>

using namespace std;

int main()

try {

throw 'a';

catch (int x) {

cout << "Caught " << x;

catch (...) {

cout << "Default Exception\n";

return 0;

}
213

Output:
Default Exception
4) If an exception is thrown and not caught anywhere, the program
terminates abnormally. For example, in the following program, a char is
thrown, but there is no catch block to catch the char.
 CPP

#include <iostream>

using namespace std;

int main()

try {

throw 'a';

catch (int x) {

cout << "Caught ";

return 0;

Output:
terminate called after throwing an instance of 'char'

This application has requested the Runtime to terminate it in an


unusual way. Please contact the application's support team for
more information.
214

We can change this abnormal termination behavior by writing our own


unexpected function.
5) A derived class exception should be caught before a base class
exception. See this for more details.
6) Like Java, the C++ library has a standard exception class which is the
base class for all standard exceptions. All objects thrown by the components
of the standard library are derived from this class. Therefore, all standard
exceptions can be caught by catching this type
7) Unlike Java, in C++, all exceptions are unchecked, i.e., the compiler
doesn’t check whether an exception is caught or not (See this for details).
So, it is not necessary to specify all uncaught exceptions in a function
declaration. Although it’s a recommended practice to do so. For example, the
following program compiles fine, but ideally the signature of fun() should list
the unchecked exceptions.
 CPP

#include <iostream>

using namespace std;

// This function signature is fine by the compiler, but not recommended.

// Ideally, the function should specify all uncaught exceptions and function

// signature should be "void fun(int *ptr, int x) throw (int *, int)"

void fun(int *ptr, int x)

if (ptr == NULL)

throw ptr;

if (x == 0)

throw x;

/* Some functionality */
215

int main()

try {

fun(NULL, 0);

catch(...) {

cout << "Caught exception from fun()";

return 0;

Output:
Caught exception from fun()
A better way to write the above code:

 CPP

#include <iostream>

using namespace std;

// Here we specify the exceptions that this function

// throws.
216

void fun(int *ptr, int x) throw (int *, int) // Dynamic Exception specification

if (ptr == NULL)

throw ptr;

if (x == 0)

throw x;

/* Some functionality */

int main()

try {

fun(NULL, 0);

catch(...) {

cout << "Caught exception from fun()";

return 0;

Note : The use of Dynamic Exception Specification has been deprecated


since C++11. One of the reasons for it may be that it can randomly abort
your program. This can happen when you throw an exception of another type
which is not mentioned in the dynamic exception specification. Your program
217

will abort itself because in that scenario, it calls (indirectly) terminate(), which
by default calls abort().
Output:
Caught exception from fun()
8) In C++, try/catch blocks can be nested. Also, an exception can be re-
thrown using “throw; “.
 CPP

#include <iostream>

using namespace std;

int main()

try {

try {

throw 20;

catch (int n) {

cout << "Handle Partially ";

throw; // Re-throwing an exception

catch (int n) {

cout << "Handle remaining ";

}
218

return 0;

Output:
Handle Partially Handle remaining
A function can also re-throw a function using the same “throw; ” syntax. A
function can handle a part and ask the caller to handle the remaining.
9) When an exception is thrown, all objects created inside the enclosing try
block are destroyed before the control is transferred to the catch block.
 CPP

#include <iostream>

using namespace std;

class Test {

public:

Test() { cout << "Constructor of Test " << endl; }

~Test() { cout << "Destructor of Test " << endl; }

};

int main()

try {

Test t1;

throw 10;
219

catch (int i) {

cout << "Caught " << i << endl;

Output:
Constructor of Test
Destructor of Test
Caught 10

Unexpected Exception:
Whenever an exception arises in C++, it is handled as per the behavior
defined using the try-catch block. However, there is often the case when an
exception is thrown but isn’t caught because the exception handling
subsystem fails to find a matching catch block for that particular exception. In
that case, the following set of actions takes place:
1. The exception handling subsystem calls the function: unexpected(). This
function, provided by the default C++ library, defines the behavior when
an uncaught exception arises. By default, unexpected calls terminate().
2. The terminate function defines the actions that are to be performed during
process termination. This, by default, calls abort().
3. The process is aborted.
The terminate() and unexpected() simply call other functions to actually
handle an error. As explained above, terminate calls abort(), and
unexpected() calls terminate(). Thus, both functions halt the program
execution when an exception handling error occurs. However, you can
change the way termination occurs.
To change the terminate handler, the function used is
set_terminate(terminate_handler newhandler), which is defined in the
header <exception>.
The following program demonstrates how to set a custom termination
handler:
220

// CPP program to set a new termination handler

// for uncaught exceptions.

#include <exception>

#include <iostream>

using namespace std;

// definition of custom termination function

void myhandler()

cout << "Inside new terminate handler\n";

abort();

int main()

// set new terminate handler

set_terminate(myhandler);

try {

cout << "Inside try block\n";

throw 100;

}
221

catch (char a) // won't catch an int exception

cout << "Inside catch block\n";

return 0;

Output:
Inside try block
Inside new terminate handler

Runtime Error:
Abort signal from abort(3) (SIGABRT)
It is to be duly noted that the only thing that your custom terminate handler
must do is stop the program execution. It must not return to the program or
resume it in any way.

Exception When Handling Exception:


Exception Handling in C++ is a process to handle runtime errors. We perform
exception handling so the normal flow of the application can be maintained even after
runtime errors.

In C++, exception is an event or object which is thrown at runtime. All exceptions are
derived from std::exception class. It is a runtime error which can be handled. If we don't
handle the exception, it prints exception message and terminates the program.

Advantage
It maintains the normal flow of the application. In such case, rest of the code is
executed even after exception.

C++ Exception Classes


222

In C++ standard exceptions are defined in <exception> class that we can use inside
our programs. The arrangement of parent-child class hierarchy is shown below:

All the exception classes in C++ are derived from std::exception class. Let's see the list
of C++ common exception classes.

Exception Description

std::exception It is an exception and parent class of all standard C++


exceptions.

std::logic_failure It is an exception that can be detected by reading a code.

std::runtime_error It is an exception that cannot be detected by reading a code.


223

std::bad_exception It is used to handle the unexpected exceptions in a c++


program.

std::bad_cast This exception is generally be thrown by dynamic_cast.

std::bad_typeid This exception is generally be thrown by typeid.

std::bad_alloc This exception is generally be thrown by new.

C++ Exception Handling Keywords


In C++, we use 3 keywords to perform exception handling:

o try
o catch, and
o throw

Resource Capture and Release:


When writing code with exceptions, it's particularly important that you always ask, "If an
exception occurs, will my resources be properly cleaned up?" Most of the time you're
fairly safe, but in constructors there's a particular problem: if an exception is thrown
before a constructor is completed, the associated destructor will not be called for that
object. Thus, you must be especially diligent while writing your constructor.

The difficulty is in allocating resources in constructors. If an exception occurs in the


constructor, the destructor doesn't get a chance to deallocate the resource. This problem
occurs most often with "naked" pointers. For example:

//: C01:Rawp.cpp
// Naked pointers.
#include
#include
using namespace std;

class Cat {
public:
Cat() { cout << "Cat()" << endl; }
~Cat() { cout << "~Cat()" << endl; }
};

class Dog {
public:
void* operator new(size_t sz) {
224

cout << "allocating a Dog" << endl;


throw 47;
}
void operator delete(void* p) {
cout << "deallocating a Dog" << endl;
::operator delete(p);
}
};

class UseResources {
Cat* bp;
Dog* op;
public:
UseResources(int count = 1) {
cout << "UseResources()" << endl;
bp = new Cat[count];
op = new Dog;
}
~UseResources() {
cout << "~UseResources()" << endl;
delete [] bp; // Array delete
delete op;
}
};

int main() {
try {
UseResources ur(3);
} catch(int) {
cout << "inside handler" << endl;
}
} ///:~
The output is
UseResources()
Cat()
Cat()
Cat()
allocating a Dog
inside handler
The UseResources constructor is entered, and the Cat constructor is successfully
completed for the three array objects. However, inside Dog::operator new( ), an
exception is thrown (to simulate an out-of-memory error). Suddenly, you end up inside
the handler, without the UseResources destructor being called. This is correct because
the UseResources constructor was unable to finish, but it also means the Cat objects
that were successfully created on the heap were never destroyed.
225

TEMPLATE AND STANDARD TEMPLATE LIBRARY

Template Classes:
A C++ template is a powerful feature added to C++. It allows you to define the generic
classes and generic functions and thus provides support for generic programming.
Generic programming is a technique where generic types are used as parameters in
algorithms so that they can work for a variety of data types.

Templates can be represented in two ways:

o Function templates
o Class templates

Function Templates:

We can define a template for a function. For example, if we have an add() function, we
can create versions of the add function for adding the int, float or double type values.

Class Template:

We can define a template for a class. For example, a class template can be created for
the array class that can accept the array of various types such as int array, float array
or double array.

Function Template
o Generic functions use the concept of a function template. Generic functions define a
set of operations that can be applied to the various types of data.
226

o The type of the data that the function will operate on depends on the type of the data
passed as a parameter.
o For example, Quick sorting algorithm is implemented using a generic function, it can
be implemented to an array of integers or array of floats.
o A Generic function is created by using the keyword template. The template defines
what function will do.

Syntax of Function Template


1. template < class Ttype> ret_type func_name(parameter_list)
2. {
3. // body of function.
4. }

Where Ttype: It is a placeholder name for a data type used by the function. It is used
within the function definition. It is only a placeholder that the compiler will
automatically replace this placeholder with the actual data type.

class: A class keyword is used to specify a generic type in a template declaration.

Let's see a simple example of a function template:

1. #include <iostream>
2. using namespace std;
3. template<class T> T add(T &a,T &b)
4. {
5. T result = a+b;
6. return result;
7.
8. }
9. int main()
10. {
11. int i =2;
12. int j =3;
13. float m = 2.3;
14. float n = 1.2;
15. cout<<"Addition of i and j is :"<<add(i,j);
16. cout<<'\n';
17. cout<<"Addition of m and n is :"<<add(m,n);
227

18. return 0;
19. }

Output:

Addition of i and j is :5
Addition of m and n is :3.5

In the above example, we create the function template which can perform the addition
operation on any type either it can be integer, float or double.

Function Templates with Multiple Parameters


We can use more than one generic type in the template function by using the comma
to separate the list.

Syntax

1. template<class T1, class T2,.....>


2. return_type function_name (arguments of type T1, T2....)
3. {
4. // body of function.
5. }

In the above syntax, we have seen that the template function can accept any number
of arguments of a different type.

Let's see a simple example:

1. #include <iostream>
2. using namespace std;
3. template<class X,class Y> void fun(X a,Y b)
4. {
5. std::cout << "Value of a is : " <<a<< std::endl;
6. std::cout << "Value of b is : " <<b<< std::endl;
7. }
8.
9. int main()
10. {
11. fun(15,12.3);
12.
228

13. return 0;
14. }

Output:

Value of a is : 15
Value of b is : 12.3

In the above example, we use two generic types in the template function, i.e., X and Y.

Overloading a Function Template


We can overload the generic function means that the overloaded template functions
can differ in the parameter list.

Let's understand this through a simple example:

1. #include <iostream>
2. using namespace std;
3. template<class X> void fun(X a)
4. {
5. std::cout << "Value of a is : " <<a<< std::endl;
6. }
7. template<class X,class Y> void fun(X b ,Y c)
8. {
9. std::cout << "Value of b is : " <<b<< std::endl;
10. std::cout << "Value of c is : " <<c<< std::endl;
11. }
12. int main()
13. {
14. fun(10);
15. fun(20,30.5);
16. return 0;
17. }

Output:

Value of a is : 10
Value of b is : 20
Value of c is : 30.5

In the above example, template of fun() function is overloaded.


229

Restrictions of Generic Functions


Generic functions perform the same operation for all the versions of a function except
the data type differs. Let's see a simple example of an overloaded function which
cannot be replaced by the generic function as both the functions have different
functionalities.

Let's understand this through a simple example:

1. #include <iostream>
2. using namespace std;
3. void fun(double a)
4. {
5. cout<<"value of a is : "<<a<<'\n';
6. }
7.
8. void fun(int b)
9. {
10. if(b%2==0)
11. {
12. cout<<"Number is even";
13. }
14. else
15. {
16. cout<<"Number is odd";
17. }
18.
19. }
20.
21. int main()
22. {
23. fun(4.6);
24. fun(6);
25. return 0;
26. }

Output:

value of a is : 4.6
Number is even
230

In the above example, we overload the ordinary functions. We cannot overload the
generic functions as both the functions have different functionalities. First one is
displaying the value and the second one determines whether the number is even or
not.

CLASS TEMPLATE
Class Template can also be defined similarly to the Function Template. When a class
uses the concept of Template, then the class is known as generic class.

Syntax

1. template<class Ttype>
2. class class_name
3. {
4. .
5. .
6. }

Ttype is a placeholder name which will be determined when the class is instantiated.
We can define more than one generic data type using a comma-separated list. The
Ttype can be used inside the class body.

Now, we create an instance of a class

1. class_name<type> ob;

where class_name: It is the name of the class.

type: It is the type of the data that the class is operating on.

ob: It is the name of the object.

Let's see a simple example:

1. #include <iostream>
2. using namespace std;
3. template<class T>
4. class A
5. {
231

6. public:
7. T num1 = 5;
8. T num2 = 6;
9. void add()
10. {
11. std::cout << "Addition of num1 and num2 : " << num1+num2<<std::endl;
12. }
13.
14. };
15.
16. int main()
17. {
18. A<int> d;
19. d.add();
20. return 0;
21. }

Output:

Addition of num1 and num2 : 11

In the above example, we create a template for class A. Inside the main() method, we
create the instance of class A named as, 'd'.

CLASS TEMPLATE WITH MULTIPLE PARAMETERS


We can use more than one generic data type in a class template, and each generic
data type is separated by the comma.

Syntax

1. template<class T1, class T2, ......>


2. class class_name
3. {
4. // Body of the class.
5. }

Let's see a simple example when class template contains two generic data types.

1. #include <iostream>
232

2. using namespace std;


3. template<class T1, class T2>
4. class A
5. {
6. T1 a;
7. T2 b;
8. public:
9. A(T1 x,T2 y)
10. {
11. a = x;
12. b = y;
13. }
14. void display()
15. {
16. std::cout << "Values of a and b are : " << a<<" ,"<<b<<std::endl;
17. }
18. };
19.
20. int main()
21. {
22. A<int,float> d(5,6.5);
23. d.display();
24. return 0;
25. }

Output:

Values of a and b are : 5,6.5


Nontype Template Arguments
The template can contain multiple arguments, and we can also use the non-type
arguments In addition to the type T argument, we can also use other types of
arguments such as strings, function names, constant expression and built-in types. Let'
s see the following example:

1. template<class T, int size>


2. class array
3. {
4. T arr[size]; // automatic array initialization.
233

5. };

In the above case, the nontype template argument is size and therefore, template
supplies the size of the array as an argument.

Arguments are specified when the objects of a class are created:

1. array<int, 15> t1; // array of 15 integers.


2. array<float, 10> t2; // array of 10 floats.
3. array<char, 4> t3; // array of 4 chars.

Let's see a simple example of nontype template arguments.

1. #include <iostream>
2. using namespace std;
3. template<class T, int size>
4. class A
5. {
6. public:
7. T arr[size];
8. void insert()
9. {
10. int i =1;
11. for (int j=0;j<size;j++)
12. {
13. arr[j] = i;
14. i++;
15. }
16. }
17.
18. void display()
19. {
20. for(int i=0;i<size;i++)
21. {
22. std::cout << arr[i] << " ";
23. }
24. }
25. };
26. int main()
234

27. {
28. A<int,10> t1;
29. t1.insert();
30. t1.display();
31. return 0;
32. }

Output:

1 2 3 4 5 6 7 8 9 10

In the above example, the class template is created which contains the nontype
template argument, i.e., size. It is specified when the object of class 'A' is created.

Points to Remember

o C++ supports a powerful feature known as a template to implement the concept of


generic programming.
o A template allows us to create a family of classes or family of functions to handle
different data types.
o Template classes and functions eliminate the code duplication of different data types
and thus makes the development easier and faster.
o Multiple parameters can be used in both class and function template.
o Template functions can also be overloaded.
o We can also use nontype arguments such as built-in or derived data types as template
arguments.

Namespace String:
 Namespace provide the space where we can define or declare identifier
i.e. variable, method, classes.
 Using namespace, you can define the space or context in which
identifiers are defined i.e. variable, method, classes. In essence, a
namespace defines a scope.

Advantage of Namespace to avoid name collision.

 Example, you might be writing some code that has a function called xyz()
and there is another library available which is also having same function
xyz(). Now the compiler has no way of knowing which version of xyz()
function you are referring to within your code.
235

 A namespace is designed to overcome this difficulty and is used as


additional information to differentiate similar functions, classes, variables
etc. with the same name available in different libraries.
 The best example of namespace scope is the C++ standard library (std)
where all the classes, methods and templates are declared. Hence while
writing a C++ program we usually include the directive using namespace
std;

Defining a Namespace:

 A namespace definition begins with the keyword namespace followed by


the namespace name as follows:
namespace namespace_name
{
// code declarations i.e. variable (int a;)
method (void add();)
classes ( class student{};)
}
 It is to be noted that, there is no semicolon (;) after the closing brace.
 To call the namespace-enabled version of either function or variable,
prepend the namespace name as follows:
 namespace_name: :code; // code could be variable , function or class.

The using directive:

 You can also avoid prepending of namespaces with the using namespace
directive. This directive tells the compiler that the subsequent code is
making use of names in the specified namespace.
 The namespace is thus implied for the following code:
 C++

#include <iostream>

using namespace std;

// first name space

namespace first_space
236

void func()

cout << "Inside first_space" << endl;

// second name space

namespace second_space

void func()

cout << "Inside second_space" << endl;

using namespace first_space;

int main ()

// This calls function from first name space.

func();

return 0;
237

Output
Inside first_space
 Names introduced in a using directive obey normal scope rules. The
name is visible from the point of the using directive to the end of the
scope in which the directive is found. Entities with the same name defined
in an outer scope are hidden.

Nested Namespaces:

 Namespaces can be nested where you can define one namespace inside
another name space as follows:
SYNTAX:
namespace namespace_name1
{
// code declarations
namespace namespace_name2
{
// code declarations
}
}
You can access members of nested namespace by using resolution
operators as follows:
// to access members of namespace_name2
using namespace namespace_name1::namespace_name2;
// to access members of namespace_name1
using namespace namespace_name1;

In the above statements if you are using namespace_name1, then it will


make elements of namespace_name2 available in the scope as follows:

 C++

#include <iostream>
238

using namespace std;

// first name space

namespace first_space

void func()

cout << "Inside first_space" << endl;

// second name space

namespace second_space

void func()

cout << "Inside second_space" << endl;

using namespace first_space::second_space;

int main ()

{
239

// This calls function from second name space.

func();

return 0;

Output
Inside second_space
Let us see how namespace scope the entities including variable and
functions:

 C++

#include <iostream>

using namespace std;

// first name space

namespace first_space

void func()

cout << "Inside first_space" << endl;

// second name space

namespace second_space
240

void func()

cout << "Inside second_space" << endl;

int main ()

// Calls function from first name space.

first_space :: func();

// Calls function from second name space.

second_space :: func();

return 0;

Output
Inside first_space
Inside second_space
Consider the following C++ program:

 CPP

// A program to demonstrate need of namespace


241

int main()

int value;

value = 0;

double value; // Error here

value = 0.0;

Output :
Compiler Error:
'value' has a previous declaration as 'int value'
In each scope, a name can only represent one entity. So, there cannot be
two variables with the same name in the same scope. Using namespaces,
we can create two variables or member functions having the same name.

 CPP

// Here we can see that more than one variables

// are being used without reporting any error.

// That is because they are declared in the

// different namespaces and scopes.

#include <iostream>

using namespace std;

// Variable created inside namespace


242

namespace first {

int val = 500;

// Global variable

int val = 100;

int main()

// Local variable

int val = 200;

// These variables can be accessed from

// outside the namespace using the scope

// operator ::

cout << first::val << '\n';

return 0;

Output
500
Definition and Creation: Namespaces allow us to group named entities that
otherwise would have global scope into narrower scopes, giving
243

them namespace scope. This allows organizing the elements of programs


into different logical scopes referred to by names. Namespaces provide the
space where we can define or declare identifiers i.e. names of variables,
methods, classes, etc.
 A namespace is a feature added in C++ and is not present in C.
 A namespace is a declarative region that provides a scope to the identifiers
(names of functions, variables or other user-defined data types) inside it.
 Multiple namespace blocks with the same name are allowed. All
declarations within those blocks are declared in the named scope.
A namespace definition begins with the keyword namespace followed by the
namespace name as follows:
namespace namespace_name
{
int x, y; // code declarations where
// x and y are declared in
// namespace_name's scope
}
 Namespace declarations appear only at global scope.
 Namespace declarations can be nested within another namespace.
 Namespace declarations don’t have access specifiers (Public or Private).
 No need to give a semicolon after the closing brace of the definition of
namespace.
 We can split the definition of namespace over several units.
Defining a Namespace:
A namespace definition begins with the keyword namespace followed by the
namespace name as follows:

 C++

namespace namespace_name{

// code declarations i.e. variable (int a;)

method (void add();)

classes ( class student{};)

}
244

It is to be noted that there is no semicolon (;) after the closing brace.


To call the namespace-enabled version of either a function or a variable,
prepend the namespace name as follows:
namespace_name: :code; // code could be a variable, function or class.

 C++

// Let us see how namespace scope the entities including variable and functions:

#include <iostream>

using namespace std;

// first name space

namespace first_space

void func()

cout << "Inside first_space" << endl;

// second name space

namespace second_space

{
245

void func()

cout << "Inside second_space" << endl;

int main ()

// Calls function from first name space.

first_space::func();

// Calls function from second name space.

second_space::func();

return 0;

// If we compile and run above code, this would produce the following result:

// Inside first_space

// Inside second_space

Output
Inside first_space
Inside second_space
The using directive:
You can avoid prepending of namespaces with the using namespace
directive. This directive tells the compiler that the subsequent code is making
246

use of names in the specified namespace. The namespace is thus implied


for the following code:

 C++

#include <iostream>

using namespace std;

// first name space

namespace first_space

void func()

cout << "Inside first_space" << endl;

// second name space

namespace second_space

void func()

cout << "Inside second_space" << endl;


247

using namespace first_space;

int main ()

// This calls function from first name space.

func();

return 0;

// If we compile and run above code, this would produce the following result:

// Inside first_space

Output
Inside first_space
Instead of accessing the whole namespace, another option (known
as using declaration) is to access a particular item within a namespace. For
example, if the only part of the std namespace that you intend to use is cout,
you can refer to it as follows:
using std::cout;
Subsequent code can refer to cout without prepending the namespace, but
other items in the std namespace will still need to be explicit as follows:
 C++
248

#include <iostream>

using std::cout;

int main ()

cout << "std::endl is used with std!" << std::endl;

return 0;

Output
std::endl is used with std!
Names introduced in a using directive obey normal scope rules, i.e., they are
visible from the point the using directive occurs to the end of the scope in
which the directive is found. Entities with the same name defined in an outer
scope are hidden.

 C++

// Creating namespaces

#include <iostream>

using namespace std;

namespace ns1 {

int value() { return 5; }

} // namespace ns1

namespace ns2 {
249

const double x = 100;

double value() { return 2 * x; }

} // namespace ns2

int main()

// Access value function within ns1

cout << ns1::value() << '\n';

// Access value function within ns2

cout << ns2::value() << '\n';

// Access variable x directly

cout << ns2::x << '\n';

return 0;

Output:
5
200
100
Classes and Namespace: The following is a simple way to create classes in
a namespace:
250

 C++

// A C++ program to demonstrate use of class

// in a namespace

#include<iostream>

using namespace std;

namespace ns

// A Class in a namespace

class geek

public:

void display()

cout<<"ns::geek::display()"<<endl;;

};

int main()

{
251

// Creating Object of geek Class

ns::geek obj;

obj.display();

return 0;

Output
ns::geek::display()
A class can also be declared inside namespace and defined outside
namespace using the following syntax:
 CPP

// A C++ program to demonstrate use of class

// in a namespace

#include <iostream>

using namespace std;

namespace ns {

// Only declaring class here

class geek;

} // namespace ns
252

// Defining class outside

class ns::geek {

public:

void display() { cout << "ns::geek::display()\n"; }

};

int main()

// Creating Object of geek Class

ns::geek obj;

obj.display();

return 0;

Output
ns::geek::display()
We can define methods as well outside the namespace. The following is
an example code:
 C++

// A C++ code to demonstrate that we can define

// methods outside namespace.

#include <iostream>

using namespace std;


253

// Creating a namespace

namespace ns {

void display();

class geek {

public:

void display();

};

} // namespace ns

// Defining methods of namespace

void ns::geek::display()

cout << "ns::geek::display()\n";

void ns::display() { cout << "ns::display()\n"; }

// Driver code

int main()

ns::geek obj;
254

ns::display();

obj.display();

return 0;

Output:
ns::display()
ns::geek::display():

Nested Namespaces:

Namespaces can be nested, i.e., you can define one namespace inside
another namespace as follows:

 C++

namespace namespace_name1 {

// code declarations

namespace namespace_name2 {

// code declarations

You can access the members of a nested namespace by using the resolution
operator (::) as follows:

 C++
255

// to access members of namespace_name2

using namespace namespace_name1::namespace_name2;

// to access members of namespace:name1

using namespace namespace_name1;

In the above statements, if you are using namespace_name1, then it will


make the elements of namespace_name2 available in the scope as follows:

 C++

#include <iostream>

using namespace std;

// first name space

namespace first_space

void func()

cout << "Inside first_space" << endl;

// second name space

namespace second_space

{
256

void func()

cout << "Inside second_space" << endl;

using namespace first_space::second_space;

int main ()

// This calls function from second name space.

func();

return 0;

// If we compile and run above code, this would produce the following result:

// Inside second_space

Output
Inside second_space
Namespace provides the advantage of avoiding name collision:-
For example, you might be writing some code that has a function called xyz()
and there is another library available in your code which also has the same
function xyz(). Now the compiler has no way of knowing which version of
257

xyz() function you are referring to within your code.


A namespace is designed to overcome this difficulty and is used as
additional information to differentiate similar functions, classes, variables,
etc. with the same name available in different libraries.
The best example of namespace scope is the C++ standard library (std),
where all the classes, methods and templates are declared. Hence, while
writing a C++ program, we usually include the directive
using namespace std;

Iterators:
Iterators are just like pointers used to access the container elements.

Important Points:
o Iterators are used to traverse from one element to another element, a process is known
as iterating through the container.
o The main advantage of an iterator is to provide a common interface for all the
containers type.
o Iterators make the algorithm independent of the type of the container used.
o Iterators provide a generic approach to navigate through the elements of a container.

Syntax

1. <ContainerType> :: iterator;
2. <ContainerType> :: const_iterator;

Operations Performed on the Iterators:


o Operator (*) : The '*' operator returns the element of the current position pointed by
the iterator.
o Operator (++) : The '++' operator increments the iterator by one. Therefore, an iterator
points to the next element of the container.
o Operator (==) and Operator (!=) : Both these operators determine whether the two
iterators point to the same position or not.
o Operator (=) : The '=' operator assigns the iterator.

Difference b/w Iterators & Pointers


258

Iterators can be smart pointers which allow to iterate over the complex data structures.
A Container provides its iterator type. Therefore, we can say that the iterators have the
common interface with different container type.

The container classes provide two basic member functions that allow to iterate or
move through the elements of a container:

o begin(): The begin() function returns an iterator pointing to the first element of the
container.
o end(): The end() function returns an iterator pointing to the past-the-last element of
the container.

Let's see a simple example:

1. #include <iostream>
2. #include<iterator>
3. #include<vector>
4. using namespace std;
5. int main()
6. {
7. std::vector<int> v{1,2,3,4,5};
8. vector<int>::iterator itr;
9. for(itr=v.begin();itr!=v.end();itr++)
10. {
11. std::cout << *itr <<" ";
12. }
13. return 0;
14. }

Output:

1 2 3 4 5
259

Iterator Categories
An iterator can be categorized in the following ways:

o Input Iterator
o Output Iterator
o Forward Iterator
o Bidirectional Iterator
o Random Access Iterator

Input Iterator: An input iterator is an iterator used to access the elements from the
container, but it does not modify the value of a container.

Operators used for an input iterator are:

o Increment operator(++)
o Equal operator(==)
o Not equal operator(!=)
o Dereference operator(*)

Output Iterator: An output iterator is an iterator used to modify the value of a


container, but it does not read the value from a container. Therefore, we can say that
an output iterator is a write-only iterator.

Operators used for an output iterator are:

o Increment operator(++)
o Assignment operator(=)
260

Forward Iterator: A forward iterator is an iterator used to read and write to a container.
It is a multi-pass iterator.

Operators used for a Forward iterator are:

o Increment operator(++)
o Assignment operator(=)
o Equal operator(=)
o Not equal operator(!=)

Bidirectional iterator: A bidirectional iterator is an iterator supports all the features of


a forward iterator plus it adds one more feature, i.e., decrement operator(--). We can
move backward by decrementing an iterator.

Operators used for a Bidirectional iterator are:

o Increment operator(++)
o Assignment operator(=)
o Equal operator(=)
o Not equal operator(!=)
o Decrement operator(--)

Random Access Iterator: A Random Access iterator is an iterator provides random


access of an element at an arbitrary location. It has all the features of a bidirectional
iterator plus it adds one more feature, i.e., pointer addition and pointer subtraction to
provide random access to an element.

Providers Of Iterators

Iterator categories Provider

Input iterator istream

Output iterator ostream

Forward iterator

Bidirectional iterator List, set, multiset, map, multimap


261

Random access iterator Vector, deque, array

Iterators and their Characteristics

Iterator Access Direction of I/O


method movement capability

Input Linear Forward only Read-only

Output Linear Forward only Write-only

Forward Linear Forward only Read/Write

Bidirectional Linear Forward & backward Read/Write

Random Random Forward & backward Read/Write

Disadvantages of iterator
o If we want to move from one data structure to another at the same time, iterators won't
work.
o If we want to update the structure which is being iterated, an iterator won?t allow us
to do because of the way it stores the position.
o If we want to backtrack while processing through a list, the iterator will not work in this
case.

Advantages of iterator
Following are the advantages of an iterator:

o Ease in programming: It is convenient to use iterators rather than using a subscript


operator[] to access the elements of a container. If we use subscript operator[] to access
the elements, then we need to keep the track of the number of elements added at the
runtime, but this would not happen in the case of an iterator.

Let's see a simple example:


262

1. #include <iostream>
2. #include<vector>
3. #include<iterator>
4. using namespace std;
5. int main()
6. {
7. vector<int> v{1,2,3,4,5};
8. vector<int>::iterator itr;
9. for(int i=0;i<5;i++) // Traversal without using an iterator.
10. {
11. cout<<v[i]<<" ";
12. }
13. cout<<'\n';
14. for(itr=v.begin();itr!=v.end();itr++) // Traversal by using an iterator.
15. {
16. cout<<*itr<<" ";
17. }
18. v.push_back(10);
19. cout<<'\n';
20. for(int i=0;i<6;i++)
21. {
22. cout<<v[i]<<" ";
23. }
24. cout<<'\n';
25. for(itr=v.begin();itr!=v.end();itr++)
26. {
27. cout<<*itr<<" ";
28. }
29. return 0;
30. }

Output:

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5 10
1 2 3 4 5 10
263

In the above example, we observe that if we traverse the elements of a vector without
using an iterator, then we need to keep track of the number of elements added in the
container.

o Code Reusability: A code can be reused if we use iterators. In the above example, if we
replace vector with the list, and then the subscript operator[] would not work to access
the elements as the list does not support the random access. However, we use iterators
to access the elements, then we can also access the list elements.
o Dynamic Processing: C++ iterators provide the facility to add or delete the data
dynamically.

Let's see a simple example:

1. #include <iostream>
2. #include<vector>
3. #include<iterator>
4. using namespace std;
5. int main()
6. {
7. vector<int> v{1,2,3,4,5}; // vector declaration
8. vector<int>::iterator itr;
9. v.insert(v.begin()+1,10);
10. for(itr=v.begin();itr!=v.end();itr++)
11. {
12. cout<<*itr<<" ";
13. }
14. return 0;
15. }

Output:

1 10 2 3 4 5

In the above example, we insert a new element at the second position by using insert()
function and all other elements are shifted by one.

Difference b/w Random Access Iterator and Other


Iterators
264

The most important difference between the Random access iterator and other iterators
is that random access iterator requires '1' step to access an element while other iterators
require 'n' steps.

Hashes:
The hash class is default constructible, which means that one can construct
this object without any arguments or initialization values. It is used to get the
hash value of the argument that is being passed to it. If the argument doesn’t
change, the value doesn’t change either.
Syntax:

template <class T> struct hash;


Syntax to create object:

hash<class template> object-name


265

Member functions: This Hash class only has one member function:

 operator(): It returns hashed value for given argument.


Below is the implementation of the hash class:
Example:

 CPP

#include <bitset>

// functional header

// for hash<class template> class

#include <functional>

#include <iostream>

#include <string>

#include <vector>

using namespace std;

// To demonstrate String Hashing

void stringHashing()

// Get the string


266

// to get its hash value

string hashing1 = "Geeks";

// Instantiation of Object

hash<string> mystdhash;

// Using operator() to get hash value

cout << "String hash values: "

<< mystdhash(hashing1)

<< endl;

// To demonstrate BITSET Hashing

void bitsetHashing()

// Get the BITSET

// to get its hash value

bitset<5> h_bitset("10101");

// Instantiation of Object
267

hash<bitset<5> > hash_bitset;

// Using operator() to get hash value

cout << "\nBitset 10101 hash value: "

<< hash_bitset(h_bitset) << endl;

// To demonstrate Vector<bool> Hashing

void vectorHashing()

// Get the Vector<bool>

// to get its hash value

vector<bool>

h_vecbool{ true, false,

true, false };

// Instantiation of Object

hash<vector<bool> > hash_vector_bool;

// Using operator() to get hash value


268

cout << "\nVector<bool> hash value: "

<< hash_vector_bool(h_vecbool)

<< endl;

// To demonstrate Char Hashing

void charHashing()

// Get the char

// to get its hash value

char ch = 'a';

// Instantiation of Object

hash<char> hash_char;

// Using operator() to get hash value

cout << "\nChar hash values: "

<< hash_char(ch)

<< endl;

}
269

// Driver Code

int main()

stringHashing();

bitsetHashing();

vectorHashing();

charHashing();

Output:
String hash values: 4457761756728957899

Bitset 10101 hash value: 17123654466142159564

Vector hash value: 16935082123893034051

Char hash values: 97

Iostreams and Other Types:

What is include iostream in C++


To perform any input and output operations in C++, we need to use iostream header
files. Without an <iostream> header file, we cannot take input from the user or print
any output.

Syntax of <iostream> header file:


270

1. #include <iostream.h>
2. #include "iostream.h"

There are two types of streams in the iostream header file

1. Input Stream: To take any input from the user, we need to use cin, which belongs to
the input stream

Syntax to use input stream:

1. std::cin>>variable_name

When the cin is executed, the cursor will be stopped at the particular statement until
the value is entered. The value entered will be stored in a variable.

2. Output Stream: To print the output, we use built-in functions in the cout output
stream

Syntax for cout

1. std::cout<<variable_name

When cout is executed, the value in the variable will be printed.

Different operations in iostream


1. Cin

Using cin, we can take input from the user and store the value in the variable. We need
to use the cin keyword followed by >> and the variable name.

Syntax:

1. std::cin>>variable_name

To use cin, we need to use #include <iostream.h> as cin belongs to this header file, and
without this, an error will occur.

Example code for cin:

1. //using header file iostream


2. #include <iostream>
3. using namespace std;
4. int main()
271

5. {
6. string name;
7. //cin declaration
8. cin >> name;
9. return 0;
10. }

Output:

Explanation:

In the above code, we used cin to take the input, so to use cin, we included
<iostream.h> header file. When the input is taken, the string input is stored in the
name variable.

2. Cout

To print the output, we need to use the cout keyword, which belongs to the iostream
header file. To use cout, we need to use the cout keyword followed by << and variable
or the statement to print the output.

The syntax for using cout:

1. std::cout<<variable_name

Example of using cout:

1. //to use the cout statement, we need to use the iostream header file
2. #include <iostream.h>
3. using namespace std;
4. int main()
5. {
6. //cout statement is used here to print the statement
7. cout << "Hi from cout statement";
272

8. return 0;}

Output:

Explanation:

In the above code, we used a cout statement to print the statement. To use the cout
statement, we need to include iostream.h header file. Once the cout is executed,
statement or variable value will be printing the output. To print any statement, we need
to use double quotes (" "), and to print a variable value; we need to use just the variable
name without double quotes(" ")

3. Cerr

Cerr is used to print errors in C++, which is present in the iostream header file. If we
need to print any error message in the code if any condition fails, then cerr is very
helpful.

The syntax for cerr is:

1. cerr<<variable_name

Example:

1. #include <iostream>
2. using namespace std;
3. int main() {
4. int a;
5. cin>>a;
6. if(a%2==0){
7. cout<<"The number entered in even number"<<endl;
8. }
273

9. else{
10. std::cerr << "Enter proper number" << '\n';
11. }
12. return 0;
13. }

Output:

Explanation:

In the above example, we used cin to take the input and check if the given number is
even or not. If the given number is not even, we need to print an error that the given
number is not an even number. We use the cerr keyword in the iostream header file to
print this error.

4. Clog:

The clog is also used to print error messages, but unlike cerr, clog is buffered, which
means the error message is stored in a buffer and then will be printed, but cerr is
unbuffered and will not store the error message in the buffer. The clog also belongs
to the iostream header file. As the clog is buffered, it will not show the error message
immediately. The clog is preferred more than cerr when efficiency is more important.

The syntax for clog:

1. clog<<variable_name;

Example:

1. #include <iostream>
2. using namespace std;
3.
4.
274

5. int main()
6. {
7. clog << "This message is stored in the buffer";
8. return 0;
9. }

Output:

Explanation:

In the above code, we are printing an error. To print this error, we use cerr, which
belongs to the iostream header file. Before printing the error, we store the error in a
buffer.

Example: For all the input and output streams

1. #include <iostream>
2. using namespace std;
3.
4. int main()
5. {
6. int a;
7. string b;
8. cin>>a;
9.
10. if(a%2==0){
11. cout<<"The number entered is even number enter a name"<<endl;
12. cin>>b;
13. cout<<b;
14. }
275

15. else{
16. std::cerr << "Enter even number" << '\n';
17.
18.
19. }
20.
21. }

Output:

Explanation: In the above code, we used all the input and output streams in the
iostream.h header file.

You might also like