KEMBAR78
001 - Ooad Full Notes | PDF | Class (Computer Programming) | C++
0% found this document useful (0 votes)
65 views133 pages

001 - Ooad Full Notes

The document outlines the course structure for Object Oriented Analysis and Design (OOAD) using C++, detailing objectives, expected outcomes, and unit topics. It covers essential concepts such as classes, objects, inheritance, polymorphism, and encapsulation, alongside practical applications in C++. The course aims to equip students with a comprehensive understanding of object-oriented development and its implementation in C++.

Uploaded by

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

001 - Ooad Full Notes

The document outlines the course structure for Object Oriented Analysis and Design (OOAD) using C++, detailing objectives, expected outcomes, and unit topics. It covers essential concepts such as classes, objects, inheritance, polymorphism, and encapsulation, alongside practical applications in C++. The course aims to equip students with a comprehensive understanding of object-oriented development and its implementation in C++.

Uploaded by

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

DEPARTMENT OF COMPUTER SCIENCE

COURSE : I M. SC - CS

PAPERCODE : 23PCSC02

PAPER NAME : OOAD

( OBJECT RIENTED ANALYSIS AND DESIGN AND C++ )

SEMESTER : I
OBJECT ORIENTED ANALYSIS
Course code 23PCSC02 L T P C
AND DESIGN & C++
Core/Elective/Supportive Core 4 4
Pre-requisite Basics of C++ and Object Oriented Concepts
Course Objectives:
The main objectives of this course are to:
1. Present the object model, classes and objects, object orientation, machine view and model
management view.
2. Enables the students to learn the basic functions, principles and concepts of object
oriented analysis and design.
3. Enable the students to understand C++ language with respect to OOAD

Expected Course Outcomes:


On the successful completion of the course, student will be able to:
Understand the concept of Object-Oriented development and modeling
1 techniques K1,K2

2 Gain knowledge about the various steps performed during object design K2,K3
3 Abstract object-based views for generic software systems K3
4 Link OOAD with C++ language K4,K5
5 Apply the basic concept of OOPs and familiarize to write C++ program K5,K6
K1 - Remember; K2 - Understand; K3 - Apply; K4 - Analyze; K5 - Evaluate; K6 – Create

Unit:1 OBJECT MODEL 15 hours


The Object Model: The Evolution of the Object Model – Elements of the Object Model –
Applying the Object Model. Classes and Objects: The Nature of an Object – Relationship among
Objects.

Unit:2 CLASSES AND OBJECTS 15 hours


Classes and Object: Nature of Class – Relationship Among classes – The Interplay of classes and
Objects. Classification: The importance of Proper Classification –identifying classes and objects
–Key Abstractions and Mechanism.

Unit:3 C++ INTRODUCTION 15 hours


Introduction to C++ - Input and output statements in C++ - Declarations -control structures –
Functions in C++.

Unit:4 INHERITANCE AND OVERLOADING 13 hours


Classes and Objects –Constructors and Destructors –operators overloading –Type Conversion-
Inheritance – Pointers and Arrays.
Unit:5 POLYMORPHISM AND FILES 15 hours
Memory Management Operators- Polymorphism – Virtual functions – Files – Exception
Handling – String Handling -Templates.

Unit:6 Contemporary Issues 2 hours


Expert lectures, online seminars – webinars

Total Lecture hours 75 hours

Text Books
“Object Oriented Analysis and Design with Applications”, Grady Booch, Second Edition,
1
Pearson Education.
“Object -Oriented Programming with ANSI & Turbo C++”, Ashok N.Kamthane, First
2
Indian Print -2003, Pearson Education.
Reference Books
1 Balagurusamy “Object Oriented Programming with C++”, TMH, Second Edition, 2003.

Related Online Contents [MOOC, SWAYAM, NPTEL, Websites etc.]


1 https://onlinecourses.nptel.ac.in/noc19_cs48/preview
2 https://nptel.ac.in/noc/courses/noc16/SEM2/noc16-cs19/
https://www.tutorialspoint.com/object_oriented_analysis_design/ooad_object_oriented_anal
3
ysis.htm

Mapping with Programming Outcomes


Cos PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10
CO1 S S S M S M S M S S
CO2 S S S M S M S M S S
CO3 S S S M S M S M S S
CO4 S S S M S M S M S S
CO5 S S S M S M S M S S

*S-Strong; M-Medium; L-Low


UNIT - I

The Object Model: The Evolution of the Object Model – Elements of the Object Model – Applying the
Object Model. Classes and Objects: The Nature of an Object – Relationship among Objects.

Objects and Classes


The concepts of objects and classes are intrinsically linked with each other and form the foundation of object–
oriented paradigm.
Object

An object is a real-world element in an object–oriented environment that may have a physical or a conceptual existenc

Identity that distinguishes it from other objects in the system.


State that determines the characteristic properties of an object as well as the values of the properties that
the object holds.
Behavior that represents externally visible activities performed by an object in terms of changes in its
state.
Objects can be modelled according to the needs of the application. An object may have a physical existence,
like a customer, a car, etc.; or an intangible conceptual existence, like a project, a process, etc.
Class
A class represents a collection of objects having same characteristic properties that exhibit common behavior. It
gives the blueprint or description of the objects that can be created from it. Creation of an object as a member of
a class is called instantiation. Thus, object is an instance of a class.
The constituents of a class are
A set of attributes for the objects that are to be instantiated from the class. Generally, different objects of a
class have some difference in the values of the attributes. Attributes are often referred as class data.
A set of operations that portray the behavior of the objects of the class. Operations are also referred as
functions or methods.
Example

Let us consider a simple class, Circle, that represents the geometrical figure circle in a two–dimensional space. The at

● x–coord, to denote x–coordinate of the center


● y–coord, to denote y–coordinate of the center
● a, to denote the radius of the circle
Some of its operations can be defined as follows
● findArea(), method to calculate area
● findCircumference(), method to calculate circumference
● scale(), method to increase or decrease the radius
During instantiation, values are assigned for at least some of the attributes. If we create an object my_circle, we
can assign values like x-coord : 2, y-coord : 3, and a : 4 to depict its state. Now, if the operation scale() is
performed on my_circle with a scaling factor of 2, the value of the variable a will become 8. This operation
brings a change in the state of my_circle, i.e., the object has exhibited certain behavior.
Encapsulation and Data Hiding
Encapsulation
Encapsulation is the process of binding both attributes and methods together within a class. Through
encapsulation, the internal details of a class can be hidden from outside. It permits the elements of the class to
be accessed from outside only through the interface provided by the class.
Data Hiding
Typically, a class is designed such that its data (attributes) can be accessed only by its class methods and
insulated from direct outside access. This process of insulating an object’s data is called data hiding or
information hiding.
Example

In the class Circle, data hiding can be incorporated by making attributes invisible from outside the class and adding tw

● setValues(), method to assign values to x-coord, y-coord, and a


● getValues(), method to retrieve values of x-coord, y-coord, and a
Here the private data of the object my_circle cannot be accessed directly by any method that is not encapsulated
within the class Circle. It should instead be accessed through the methods setValues() and getValues().
Message Passing
Any application requires a number of objects interacting in a harmonious manner. Objects in a system may
communicate with each other using message passing. Suppose a system has two objects: obj1 and obj2. The
object obj1 sends a message to object obj2, if obj1 wants obj2 to execute one of its methods.
The features of message passing are
● Message passing between two objects is generally unidirectional.
● Message passing enables all interactions between objects.
● Message passing essentially involves invoking class methods.
● Objects in different processes can be involved in message passing.
Inheritance
Inheritance is the mechanism that permits new classes to be created out of existing classes by extending and
refining its capabilities. The existing classes are called the base classes/parent classes/super-classes, and the new
classes are called the derived classes/child classes/subclasses. The subclass can inherit or derive the attributes
and methods of the super-class(es) provided that the super-class allows so. Besides, the subclass may add its
own attributes and methods and may modify any of the super-class methods. Inheritance defines an “is – a”
relationship.
Example
From a class Mammal, a number of classes can be derived such as Human, Cat, Dog, Cow, etc. Humans, cats,
dogs, and cows all have the distinct characteristics of mammals. In addition, each has its own particular
characteristics. It can be said that a cow “is – a” mammal.
Types of Inheritance

Single Inheritance
Multiple Inheritance
Multilevel Inheritance

Hierarchical Inheritance

Hybrid Inheritance

The following figure depicts the examples of different types of inheritance.


Polymorphism
Polymorphism is originally a Greek word that means the ability to take multiple forms. In object-oriented
paradigm, polymorphism implies using operations in different ways, depending upon the instance they are
operating upon. Polymorphism allows objects with different internal structures to have a common external
interface. Polymorphism is particularly effective while implementing inheritance.
Example
Let us consider two classes, Circle and Square, each with a method findArea(). Though the name and purpose
of the methods in the classes are same, the internal implementation, i.e., the procedure of calculating area is
different for each class. When an object of class Circle invokes its findArea() method, the operation finds the
area of the circle without any conflict with the findArea() method of the Square class.
Generalization and Specialization
Generalization and specialization represent a hierarchy of relationships between classes, where subclasses
inherit from super-classes.
Generalization
In the generalization process, the common characteristics of classes are combined to form a class in a higher
level of hierarchy, i.e., subclasses are combined to form a generalized super-class. It represents an “is – a – kind
– of” relationship. For example, “car is a kind of land vehicle”, or “ship is a kind of water vehicle”.
Specialization
Specialization is the reverse process of generalization. Here, the distinguishing features of groups of objects are
used to form specialized classes from existing classes. It can be said that the sub classes are the specialized
versions of the super-class.
The following figure shows an example of generalization and specialization.

Links and Association


Link
A link represents a connection through which an object collaborates with other objects. Rumbaugh has defined
it as “a physical or conceptual connection between objects”. Through a link, one object may invoke the methods
or navigate through another object. A link depicts the relationship between two or more objects.
Association
Association is a group of links having common structure and common behavior. Association depicts the
relationship between objects of one or more classes. A link can be defined as an instance of an association.
Degree of an Association
Degree of an association denotes the number of classes involved in a connection. Degree may be unary, binary,
or ternary.

A unary relationship connects objects of the same class.


A binary relationship connects objects of two classes.
A ternary relationship connects objects of three or more classes.

Cardinality Ratios of Associations


Cardinality of a binary association denotes the number of instances participating in an association. There are three typ

One–to–One
One–to–Many
Many–to–Many

Aggregation or Composition
Aggregation or composition is a relationship among classes by which a class can be made up of any
combination of objects of other classes. It allows objects to be placed directly within the body of other classes.
Aggregation is referred as a “part–of” or “has–a” relationship, with the ability to navigate from the whole to its
parts. An aggregate object is an object that is composed of one or more other objects.
Example

In the relationship, “a car has–a motor”, car is the whole object or the aggregate, and the motor is a “part–of” the car.

Physical containment

Conceptual containment

Benefits of Object Model


Now that we have gone through the core concepts pertaining to object orientation, it would be worthwhile to
note the advantages that this model has to offer.
The benefits of using the object model are
It helps in faster development of software.
It is easy to maintain. Suppose a module develops an error, then a programmer can fix that particular
module, while the other parts of the software are still up and running.
It supports relatively hassle-free upgrades.
It enables reuse of objects, designs, and functions.
It reduces development risks, particularly in integration of complex systems.

Frameworks
 Way of delivering application development patterns to
support best practice sharing during application
development.
 Can be viewed as the implementation of a system of
design patterns.
Why we model
The importance of Modeling:
A model is a simplification of reality. A model provides the blueprints of a system. Every
system may be described from different aspects using different models, and each model is
therefore a semantically closed abstraction of the system.
A model may be structural, emphasizing the organization of the system, or it may be
behavioral, emphasizing the dynamics of the system. We build models so that we can better
understand the system we are developing.
Through modeling, we achieve four aims.
1. Models help us to visualize a system as it is or as we want it to be.
2. Models permit us to specify the structure or behavior of a system.
3. Models give us a template that guides us in constructing a system.
4. Models document the decisions we have made.
Modeling is not for big systems. Even the software equivalent of a dog house can
benefit from some modeling. For example if you want to build a dog house ,you can start with a
pile of lumber, some nails, and a basic tools, such as a hammer,saw,and a tape measure. In few
hours, with little prior planning, you will likely
end up a with a dog house that's reasonably functional. finally your will happy and get a less
demanding dog.
if you want to build a house for your family , you can start with a pile of lumber, some
nails, and a basic tools. But it's going to take you a lot longer, and your family will certainly be
more demanding than the dog. If you want to build a quality house that meets the needs of
your family and you will need to draw some blue prints.

EVOLUTION OF OBJECT MODEL


ELEMENTS OF OBJECTS:

Elements of the Object Model

The four major elements of the object model (the conceptual framework of an object-oriented thing) are —

1. Abstraction
2. Encapsulation
3. Modularity
4. Hierarchy
and the three minor elements are —

1. Typing
2. Concurrency
3. Persistence.
The major elements are essential whereas the minor ones are useful but not essential. Now we try to elaborately
define major elements and minor elements.

Major Elements

The major elements are listed below.

1. Abstraction
Abstraction is one of the fundamental way in which we as humans cope with complexity. An abstraction
denotes the essential characteristics of an object that distinguish it from all other kinds of objects. Thus it
provides crisply defined conceptual boundaries, relative to the perspective of the viewer.

We can characterize the behavior of an object by considering the services that it provides to other objects as
well as the operations that it may perform upon other objects. A protocol denotes the way in which an object
may act or react and thus constitutes the entire static and dynamic outside view of the abstraction.

2. Encapsulation

Encapsulation is the process of compartmentalizing the elements of an abstraction that constitutes its structure
and behavior. Encapsulation serves to separate the contractual interface of an abstraction and its
implementation. Abstraction and encapsulations are complimentary concepts.

3. Modularity

Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled
modules.

4. Hierarchy

Hierarchy is a ranking of ordering of abstractions. The two most important hierarchies in a complex system are
its class structure (‘is a’ or Generalization/specialization) and object structure (‘part of’ or whole part).
Inheritance is the most important ‘is a” hierarchy. Basically inheritance defines a relationship among classes
wherein one class shares the structure or behavior defined in one or more classes.

Minor Elements

The minor elements are listed below.

Typing

Concepts of typing derive primarily from theories of abstract data types. A type is a precise characterization of
structural or behavioral which a collection of entities all share. Typing is the enforcement of the class of an
object, such that objects of different types may not be interchanged, or at the most, they may be interchanged
only in very restricted ways.

Concurrency

It is the property that distinguishes an active object from one that is not active.

Persistence

Is the property of an object through which its existence transcends time (i.e. the object continues to exist after
its creator ceases to exist) and/or space (i.e. the object’s location moves from the address space in which it was
created).
CLASSES AND OBJECTS:
UNIT - III

Introduction to C++ - Input and output statements in C++ - Declarations -control structures – Functions in C++

Introduction to C++ Programming Language

✔ C++ is a general-purpose programming language that was developed as an enhancement of the C language
to include object-oriented paradigm. It is an imperative and a compiled language.

✔ C++ is a high-level, general-purpose programming language designed for system and application
programming. It was developed by Bjarne Stroustrup at Bell Labs in 1983 as an extension of the C
programming language. C++ is an object-oriented, multi-paradigm language that supports procedural,
functional, and generic programming styles.
✔ One of the key features of C++ is its ability to support low-level, system-level programming, making it
suitable for developing operating systems, device drivers, and other system software. At the same time, C+
+ also provides a rich set of libraries and features for high-level application programming, making it a
popular choice for developing desktop applications, video games, and other complex applications.
✔ C++ has a large, active community of developers and users, and a wealth of resources and tools available
for learning and using the language. Some of the key features of C++ include:
✔ Object-Oriented Programming: C++ supports object-oriented programming, allowing developers to create
classes and objects and to define methods and properties for these objects.
✔ Templates: C++ templates allow developers to write generic code that can work with any data type, making
it easier to write reusable and flexible code.
✔ Standard Template Library (STL): The STL provides a wide range of containers and algorithms for
working with data, making it easier to write efficient and effective code.
✔ Exception Handling: C++ provides robust exception handling capabilities, making it easier to write code
that can handle errors and unexpected situations.

✔ Overall, C++ is a powerful and versatile programming language that is widely used for a range of
applications and is well-suited for both low-level system programming and high-level application
development.

Here are some simple C++ code examples to help you understand the language:

1.Hello World:

C++
#include <iostream>

int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Output
Hello, World!

C++ is a middle-level language rendering it the advantage of programming low-level (drivers, kernels) and even
higher-level applications (games, GUI, desktop apps etc.). The basic syntax and code structure of both C and
C++ are the same.

Some of the features & key-points to note about the programming language are as follows:

✔ Simple: It is a simple language in the sense that programs can be broken down into logical units and parts,
has a rich library support and a variety of data-types.
✔ Machine Independent but Platform Dependent: A C++ executable is not platform-independent
(compiled programs on Linux won’t run on Windows), however they are machine independent.
✔ Mid-level language: It is a mid-level language as we can do both systems-programming (drivers, kernels,
networking etc.) and build large-scale user applications (Media Players, Photoshop, Game Engines etc.)
✔ Rich library support: Has a rich library support (Both standard ~ built-in data structures, algorithms etc.)
as well 3rd party libraries (e.g. Boost libraries) for fast and rapid development.
✔ Speed of execution: C++ programs excel in execution speed. Since, it is a compiled language, and also
hugely procedural. Newer languages have extra in-built default features such as garbage-collection,
dynamic typing etc. which slow the execution of the program overall. Since there is no additional
processing overhead like this in C++, it is blazing fast.
✔ Pointer and direct Memory-Access: C++ provides pointer support which aids users to directly manipulate
storage address. This helps in doing low-level programming (where one might need to have explicit control
on the storage of variables).
✔ Object-Oriented: One of the strongest points of the language which sets it apart from C. Object-Oriented
support helps C++ to make maintainable and extensible programs. i.e. Large-scale applications can be built.
Procedural code becomes difficult to maintain as code-size grows.
✔ Compiled Language: C++ is a compiled language, contributing to its speed.

✔ Applications of C++:
C++ finds varied usage in applications such as:

✔ Operating Systems & Systems Programming. e.g. Linux-based OS (Ubuntu etc.)

✔ Browsers (Chrome & Firefox)

✔ Graphics & Game engines (Photoshop, Blender, Unreal-Engine)

✔ Database Engines (MySQL, MongoDB, Redis etc.)

✔ Cloud/Distributed Systems

Here are some key points to keep in mind while working with C++:

Object-Oriented Programming: C++ is an object-oriented programming language, which means that it allows
you to define classes and objects to model real-world entities and their behavior.
Strong Type System: C++ has a strong type system, which means that variables have a specific type and that
type must be respected in all operations performed on that variable.
Low-level Access: C++ provides low-level access to system resources, which makes it a suitable choice for
system programming and writing efficient code.
Standard Template Library (STL): The STL provides a large set of pre-written algorithms and data structures
that can be used to simplify your code and make it more efficient.
Cross-platform Compatibility: C++ can be compiled and run on multiple platforms, including Windows,
MacOS, and Linux, making it a versatile language for developing cross-platform applications.
Performance: C++ is a compiled language, which means that code is transformed into machine code before it
is executed. This can result in faster execution times and improved performance compared to interpreted
languages like Python.
Memory Management: C++ requires manual memory management, which can lead to errors if not done
correctly. However, this also provides more control over the program’s memory usage and can result in more
efficient memory usage.
Syntax: C++ has a complex syntax that can be difficult to learn, especially for beginners. However, with
practice and experience, it becomes easier to understand and work with.
These are some of the key points to keep in mind when working with C++. By understanding these concepts,
you can make informed decisions and write effective code in this language.

Advantages of C++:

Performance: C++ is a compiled language, which means that its code is compiled into machine-readable code,
making it one of the fastest programming languages.
Object-Oriented Programming: C++ supports object-oriented programming, which makes it easier to write
and maintain large, complex applications.
Standard Template Library (STL): The STL provides a wide range of algorithms and data structures for
working with data, making it easier to write efficient and effective code.
Machine Independent: C++ is not tied to any hardware or processor. If the compiler compiles the program in
the system, it will be able to run no matter what the hardware is.
Large Community: C++ has a large, active community of developers and users, providing a wealth of
resources and support for learning and using the language.

Disadvantages of C++:

Steep Learning Curve: C++ can be challenging to learn, especially for beginners, due to its complexity and the
number of concepts that need to be understood.
Verbose Syntax: C++ has a verbose syntax, which can make code longer and more difficult to read and
maintain.
Error-Prone: C++ provides low-level access to system resources, which can lead to subtle errors that are
difficult to detect and fix.

Reference Books:

“The C++ Programming Language” by Bjarne Stroustrup


“Effective C++: 55 Specific Ways to Improve Your Programs and Designs” by Scott Meyers
“C++ Primer Plus” by Stephen Prata
“C++ For Dummies” by Stephen R. Davis
“Data Structures and Algorithm Analysis in C++” by Mark Allen Weiss
Some interesting facts about C++:
Here are some awesome facts about C++ that may interest you:
The name of C++ signifies the evolutionary nature of the changes from C. “++” is the C increment operator.
C++ is one of the predominant languages for the development of all kind of technical and commercial software.
C++ introduces Object-Oriented Programming, not present in C. Like other things, C++ supports the four
primary features of OOP: encapsulation, polymorphism, abstraction, and inheritance.
C++ got the OOP features from Simula67 Programming language.
A function is a minimum requirement for a C++ program to run.(at least main() function)

C++ Basic Input/Output


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

I/O Library Header Files


Let us see the common header files used in C++ programming are:
Backward Skip 10sPlay VideoForward Skip 10s
Header Function and Description
File

<iostream> It is used to define the cout, cin and cerr objects, which correspond to standard output
stream, standard input stream and standard error stream, respectively.
<iomanip> It is used to declare services useful for performing formatted I/O, such as setprecision and
setw.
<fstream> It is used to declare services for user-controlled file processing.

Standard output stream (cout)


The cout is a predefined object of ostream class. It is connected with the standard output device, which is
usually a display screen. The cout is used in conjunction with stream insertion operator (<<) to display the
output on a console
Let's see the simple example of standard output stream (cout):

#include <iostream>
using namespace std;
int main( ) {
char ary[] = "Welcome to C++ tutorial";
cout << "Value of ary is: " << ary << endl;
}
Output:
Value of ary is: Welcome to C++ tutorial

Standard input stream (cin)


The cin is a predefined object of istream class. It is connected with the standard input device, which is usually a
keyboard. The cin is used in conjunction with stream extraction operator (>>) to read the input from a console.
Let's see the simple example of standard input stream (cin):

#include <iostream>
using namespace std;
int main( ) {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl;
}
Output:
Enter your age: 22
Your age is: 22

Standard end line (endl)


The endl is a predefined object of ostream class. It is used to insert a new line characters and flushes the stream.
Let's see the simple example of standard end line (endl):

#include <iostream>
using namespace std;
int main( ) {
cout << "C++ Tutorial";
cout << " Javatpoint"<<endl;
cout << "End of line"<<endl;
}
Output:
C++ Tutorial Javatpoint
End of line

Basic Input / Output in C++:


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.

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

iostream: iostream stands for standard input-output stream. This header file contains definitions of objects like
cin, cout, cerr, etc.
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.
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.
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 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(<<).

Variables declaration in C++:

C++ offer a rich assortment of built-in as well as user defined data types.
Integer, a built-in type, represents a whole number value. Define integer using the keyword int.

C++ requires that you specify the type and the identifier for each variable defined.

An identifier is a name for a variable,function,class, module, or any other user-defined item. An identifier starts
with a letter(A-Z or a-z) or an underscore (_), followed by additional letters, underscore, and digits (0 to 9).
For example:
Define a variable called var that can hold integer values as follows:

int var=10;

Now, let's assign a value to the variable and print it.


#include<iostream.h>
using namespace std;
int main()
{
int var=10;
cout<<var;
return 0;
}
Output:
10
Note: The C++ programming language is case-sensitive, so var, Var and VAR are different-different identifiers.
Define all variables with a name and a data type before using them in a program. In cases in which you have
multiple variables of the same type, it's possible to define them in one declaration, separation, separating them
with commas(,).

For example:

int a,b;
// define two variables of type int
A variable can be assigned a value, and can be used to perform operations.
For example:
int a=30;
int b=15;
int sum =a+b;
cout<<sum;
// Now sum equals 45
C++ Variables

Variables are containers for storing data values.

In C++, there are different types of variables (defined with different keywords), for example:

● int - stores integers (whole numbers), without decimals, such as 123 or -123
● double - stores floating point numbers, with decimals, such as 19.99 or -19.99
● char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
● string - stores text, such as "Hello World". String values are surrounded by double quotes
● bool - stores values with two states: true or false

Declaring (Creating) Variables

To create a variable, specify the type and assign it a value:

Syntax

type variableName = value;

Where type is one of C++ types (such as int), and variableName is the name of the variable (such
as x or myName). The equal sign is used to assign values to the variable.

To create a variable that should store a number, look at the following example:

Example

Create a variable called myNum of type int and assign it the value 15:

int myNum = 15;


cout << myNum;

Try it Yourself »

You can also declare a variable without assigning the value, and assign the value later:

Example

int myNum;
myNum = 15;
cout << myNum;
Try it Yourself »

Note that if you assign a new value to an existing variable, it will overwrite the previous value:

Example

int myNum = 15; // myNum is 15


myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10

https://www.slideshare.net/yndaravind/classes-and-objects-238607159

What is Control Structure in C++?

In C++, along with Conditional Control Structures, we also have the Iteration or Loop Control Structure.

Types of Control Structure in C++

There are three types of Control Structures in C++, And all the program processes we write can only be
implemented with these three control structures.

Sequence Structure

This is the most simple and basic form of a control structure. It is simply the plain logic we write; it only has
simple linear instructions, no decision making, and no loop. The programs we all wrote at the start of our
programming journey were this control structure only. It executes linearly line by line in a straight line manner.
See the below code
#include <iostream>using namespace std;int main() { int num1 = 4; int num2 = 7; // Declaring and
intializing two int variables. int sum; // Declaring an int variable "sum". sum = num1 + num2; // Adding
num1 and num2 and equating it to the sum variable. cout << sum << endl; // Printing the sum. return 0;}

Try it yourself

Output:
11
Let's understand the program flow and how it happened.

● Firstly, num1 and num2 were declared and initialized.


● Then, the sum variable was declared and was assigned the numerical sum of num1 and num2.
● We are then printing the sum.
We can see that our program came one way, in a straight-line manner, with no bending, no reverse, simply a
straight flow. This is simply what Sequence Control Structures are.

Selection Structure

Sometimes in our program, we will need to write certain condition checks that this part of code should only
execute if a particular condition meets or another part of code should run.
For example: The example we took at the start is that we have to write a program that will validate if a user is
eligible to drive or not based on two conditions:

● if the age is equal to or above 18


● if the user has their driving license

Let's understand it with the help of a program


#include <iostream>using namespace std;
int main() {
// Declaring two int variables to store age and if the user has the driving license.
int age, hasDrivingLicense;
cout << "Please Enter your Age : ";
cin >> age; cout << "Are you having your Driving License, enter 1 for 'yes', 0 for 'no' : "; cin >>
hasDrivingLicense; // Taking the user input.
// Checking the condition.
if (age >= 18 && hasDrivingLicense == 1) {
// If fulfilled, then executing if part of the code.
cout << "Yes, you are Allowed to Drive" << endl;
}
else {
// Else, executing else part of the code.
cout << "Sorry, you are not Allowed to Drive" << endl;
}
return 0;
}

Output:
Please Enter your Age : 20Are you having your Driving License, enter 1 for 'yes', 0 for 'no' : 1
Yes, you are Allowed to Drive
Here,
● We are first asking the user to enter their age and then ask if they have a driving license.
● Then we are checking the condition using an if-else control statement, and if it satisfies, then executing
the first block of code, else executing the other block of the code.

A block means a group of statements enclosed in curly brackets {....}, and those specific statements are part of
that specific block.
In C++, we have two types of Selection Control statements:

● If else statements
● Switch case statements We will be understanding in-depth about each of these in the coming section.

Loop Structure

Suppose we are asked to write a program that prints "Hello World" once. We will simply write it as:
#include <iostream>using namespace std;int main(){ cout << "Hello World" << endl; return 0;}
Now, we are asked to write a program that will print "Hello World" 10 times; we can write it as
#include <iostream>using namespace std;int main() { cout << "Hello World" << endl; // 1 time cout <<
"Hello World" << endl; // 2 time cout << "Hello World" << endl; // .. cout << "Hello World" << endl; // ..
cout << "Hello World" << endl; // .. cout << "Hello World" << endl; // .. cout << "Hello World" <<
endl; // .. cout << "Hello World" << endl; // .. cout << "Hello World" << endl; // .. cout << "Hello World"
<< endl; // 10 times return 0;}

Output:
Hello WorldHello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
But this seems like, a lot of repetition, but we can manage it somehow.
Now, what if we have to print it 100 or, let's say, 1000 times? Are we going to copy-paste the same line 1000
times? No, that will not be feasible. There comes the use of loop control structures.
Whenever in our program we see that a certain piece of code is being repeated repeatedly, then we can enclose
that in a loop structure and provide the condition that this code should execute these specific number of times.
Taking the above example, suppose we are asked to write a program that will print "Hello World" 1000 times.
#include <iostream>using namespace std;int main() { int num; // Declaring the num variable to store how
many times the user wants the loop to run. cout << "Enter how many you want to print : \n"; cin >> num; //
Taking the user input. for (int i = 0; i < num; i++) { // Printing it till the condition is met. cout <<
"Hello World" << endl; }
return 0;}

Try it yourself

Input:
1000
Output:
Hello WorldHello World
Hello World 1000 times

We have three types of Loops in C++:

● While Loop
● Do While Loop

For Loop

Control statements in C/C++ to Implement Control Structures

Conditional Statements

In general, we have two types of conditional statements in C++:

● if statements
● if else-if ladder

if conditional statements Sometimes we only want to check one condition, and if it meets, we want to process
some statements.
Syntax:
if [condition to be checked] { // Statements to run.}
Example:
#include <iostream>using namespace std;int main() { int age; // Declaring age variable. cout << "Enter your
age : "; cin >> age; // Taking the user input. // Checking the condition inside if expression. if (age >= 18) {
// Printing if the condition is satisfied. cout << "You can drive" << endl; }
return 0;}

Output:
Enter your age : 20You can drive
From this, we can also see that the else part inside an if-else statement is optional.
if else-if ladder Unlike above, here we check for multiple cases.
Syntax:
if [condition to be checked] { // Statements to run.} else if [statements to be checked] { // Statements to
run.}
...else { // Statements to run.}
Example:
#include <iostream>using namespace std;int main() { int age; // Declaring age variable cout << "Enter your
age : "; cin >> age; // Taking the user input // Checking the condition inside each expression if (age == 18)
{ // Printing if the condition satisfies cout << "Your age is 18" << endl; } else if (age > 18)
{ cout << "Age is greater than 18" << endl; } else { cout << "Age is neither equal to nor greater than
18" << endl; }
return 0;}

Try it yourself

Output:
Enter your age : 18Your age is 18
Explanation: Here, first, we are reading the user's age from the console. Then we check if the age is 18. In that
case, we print "Your age is 18". If the age is greater than 18, then we print a similar message. If both the above
conditions are false, the age is smaller than 18, and we notify the user with a similar message.

Iteration Statements
As discussed above, sometimes, in our program, when we want to repeat a certain set of instructions, we can
wrap them inside a loop. In C++, we have three types of iteration or loop statements:

● While loop
● Do while loop
● For loop

while loop While loop is used when we want to run a loop till a condition is evaluated to be true
Syntax:
while [condition of loop] { // statements to run}
Example:
#include <iostream>using namespace std;int main() { int end; // Declaring the end variable. cout << "Enter
the number till which you want to print : "; cin >> end; // Taking the user input. int start = 1; // Initialzing
the start. // Loop start while (start <= end) // Termination condition { // Statements. cout << start
<< endl; // Incrementing the start variable, so that at some point loop condition // becomes false, and
the program exits the loop. start++;
}
return 0;}

Try it yourself

Input:
10
Output:
123..
..10
do-while loop This is the same as the while loop. The only difference is that the loop runs at least once, whether
the condition is true or false.
Syntax:
do { // Statements to run.} while (condition to be checked);
Example:
#include <iostream>using namespace std;int main() { int end; // Declaring the end variable. cout << "Enter
the number till which you want to print : "; cin >> end; // Taking the user input. int start = 12; // Initialzing
the start. // Loop termination condition. do { // Statements cout << start << endl; //
incrementing the start variable, so that at some point loop condition // becomes false, and the program
exits the loop start++;
} while (start <= end); // Even if the condition is false, still, // the loop will run once and will print 12.
return 0;}

Try it yourself

Input
10
Output:
12
for loop for loop is used when we are exactly sure in numbers for how many times our loop has to run.
Syntax:
for(initialization; termination; increment or decrement) { // Statements to run.}
Example:
Jump Statements
As the name suggests, jump statements are used to jump out of a block of code, be it a conditional statement, an
iteration statement, or something else. In C++, we generally have 4 types of jump statements:

● break
● continue
● goto
● exit()

break statements Moves the program flow out of the current block when encountered.
Example:
#include <iostream>using namespace std;int main() { // Loop statement start. for (int i = 0; i < 10; i++) {
// If the condition is met. if (i == 5) { // When a break statement is encountered, the program will exit
the loop. break; }
cout << i << endl; // Printing the i's value. }
return 0;}

Try it yourself

Output:
01234
The point to remember is that it only exits the first block or block in scope, i.e., if we are in nested blocks,
which means, block inside a block, then it will only exit the most inner block.
continue statement When encountered, it just skips that particular iteration, which means we are telling the
compiler that as soon as you see the continue statement, forget everything written below it for that iteration, and
start with the next iteration.
Example:
#include <iostream>using namespace std;int main() { // Loop statement start. for (int i = 0; i < 10; i++) {
// If the condition is met. if (i == 5) { // When continue statement will be encountered, // the
program will skip that iteration. continue; }
cout << i << endl; // Printing the i's value. }
return 0;}

Try it yourself

Output:
012346789
We can see that after the condition of i == 5 matches, and the program encounters the continue statement, it
skipped that particular iteration by skipping 5 in the output.
goto statement the goto statement is used to move the program flow to a user-defined label. The use of goto is
discouraged, as it sometimes confuses fellow programmers and those who will read our code.
Example:
#include <iostream>using namespace std;int main() { int num = 0; // Initializing num variable. start: //
Defining the label. cout << num << endl; num++; // Incrementing num variable. // Checking condition.
if (num < 10) { // If true, execute the goto statement, and move to label "start". goto start; }
cout << "End Reached"; // Finally printing return 0;}

Try it yourself
Output:
0123456789End Reached
We can see that goto can be used as a loop, along with a jump statement, but it is advised to avoid the use
of goto statements.
exit() function The purpose of using exit() is to terminate or exit the current program with a specific exit code.
Example:
#include <iostream>using namespace std;int main() { for (int i = 0; i < 10; i++) { if (i == 5) {
exit(0); }
cout << i << endl;
}
return 0;}

Try it yourself

Output:
01234
It will exit the program, and the value we have supplied to the exit() function, here 0, will be returned to the
operating system as the program's exit code.

Switch Statements

Switch statements are like if-else statements only, but the difference here is that they check for specific
individual cases, unlike if-else statements, which also check for logical expressions.
Syntax:
switch(expression) { case value1: // statements to run break; case value2: // statements to run
break; ..
..
.. default: // statements to run }
Example:
#include <iostream>using namespace std;int main() { int num; // Declaring num variable. cout << "Enter a
number : "; cin >> num; // Taking the user input. // Switch expression starts. switch (num) { //
Checking for individual cases. case 1: cout << "The number is 1" << endl; break; case 2: cout
<< "The number is 2" << endl; break; case 5: cout << "The number is 5" << endl; break;
default: cout << "The number is neither 1 nor 2 nor 5" << endl; }
return 0;}

Try it yourself

Input:
2
Output:
The number is 2
Both the if-else and switch statements are selection statements and are used to transfer the flow of the program
to a specific block of statements upon certain conditions being met. But they indeed have some minor
differences. Let's now understand them.
Differences between if-else and switch statements

● Generally, the expression inside if-else statements are used to decide whether to run their respective
block of code if a condition is being met, for example, if (age >= 18) or if (age < 60). On the other hand,
in switch statements, we check for individual cases, i.e., case: 18, case: 19, or case: 60.
● In if statements, we can place multiple checks inside the same expression using && operator, whereas in
switch statements, we can only check one case at a time.
● If else expressions check for equality and logical expression, whereas switch checks only for equality.

● If else statements can evaluate integers, floating-point values, characters, booleans, etc., whereas switch
statements can only evaluate integer or character datatype.
● With if-else statements, the program flow is always like, either if block will execute or else-if will
execute or else will execute, which means only 1 block will execute from the if-else ladder.
● On the other hand, in switch statements, we can execute all the cases below the matched case if the
break statements are not applied.
● It's time taking and challenging to modify if-else expressions if we want to change the respective cases
because tracing down which case is responsible for that specific task can take some time, whereas,
with switch statements, it is easy, as here, we are checking for individual cases only. Hence, it's easy to
track down the required expression.

True and False

Until now, we have understood the selection and iteration control statements, how each function, and how the
code executes.
But the most important part here is the conditions; both works on certain conditions being evaluated as true or
false, and both involve decision-making steps. C++ has a built-in datatype bool, specifically designed to
hold true and false values.
All the statements that we have studied till now, internally, are evaluated as booleans only. In C++, the value 0
is considered false and the value 1 is considered true.

Logical Operators

We will not always have simple condition checks in our program, like age >= 18 or num < 10, sometimes, we
will be in need to check even more complex conditions, we might have to chain two or more conditions
together; In that case, we will be using logical operators. We have three types of logical operators in C++:

● && (logical and operator)


● || (logical or operator)
● ! (logical not operator)

Logical AND Operator (&&)

It is a binary operator, i.e., it needs two operands and is evaluated as true only if both the operands are true.
Syntax:
[condition1 && condition2]
Example:
#include <iostream>using namespace std;int main() { int num; // Declaring the num variable. cout <<
"Enter a number : "; cin >> num; // Taking the user input. // Checking the condition. if (num >= 10 &&
num < 20) { cout << "The number is between 10 and 20" << endl; } else { cout << "The number is
not between 10 and 20" << endl; }
return 0;}
Try it yourself

Input:
12
Output:
The number is between 10 and 20
We can see that only if both the conditions are true, i.e., num is greater than or equal to 10 and num is less
than 20, then only the condition will be true.
Truth Table:
condition1 condition2 condition1 && condition2
true true true
true false false
false true false
false false false

Logical OR Operator (||)

It evaluates to true if at least one of the operands is true.


Syntax:
[condition1 || condition2]
Example:
#include <iostream>using namespace std;int main() { int num; // Declaring the num variable. cout <<
"Enter a number : "; cin >> num; // Taking the user input. // Checking the condition. if (num >= 10 || num
< 20) { cout << "The number is either greater than or equal to 10 or less than 20" << endl; } else
{ cout << "In this case, the if condition will always be true, so else will never be executed" << endl; }
return 0;}

Try it yourself

Input:
22
Output:
The number is either greater than or equal to 10 or less than 20
We can see that if either of the two conditions is true, i.e., num is greater than or equal to 10 or num is less
than 20, then only the condition will be true.
Truth Table:
condition1 condition2 condition1 && condition2
true true true
true false true
false true true
false false false

Logical NOT Operator (!)

It is a unary operator and reverses the truth value of its operand.


Syntax:
[!condition]
Example:
#include <iostream>using namespace std;int main() { bool isTrue = true; // intializing a boolean variable
isTrue as true isTrue = !isTrue; // now the value of isTrue is false if (isTrue == true) { cout << "If case
executed" << endl; } else { cout << "Else case executed" << endl; }
return 0;}
Output:
Else case executed

Conditional Operator

Also called a Ternary Operator, when sometimes we just want to do a small and short check and do not want
to write the long syntax of if-else or switch statements, then we can simply use the ternary conditional
operator.
Syntax:
condition ? statements if true : statements if false
Example:
#include <iostream>using namespace std;int main() { int age; // Initialzing the age variable. cout << "Enter
your age : "; cin >> age; // Taking the user input. // Checking the condition using conditional operator. age
>= 18 ? cout << "You can vote" : cout << "You cannot vote"; return 0;}

Input:
20
Output:
You can vote

Conclusion

● Control Structures are used to alter the flow of the program based on certain conditions being met or not.
● In C++, we mainly talk about selection and loop control structures.
● There are two selection control structures, if-else ladder and switch statements. Here the if-else checks
for equality and logical expressions, whereas switch only checks for equality.
● In C++, we have three types of loops: while, do-while, and for loop. while and do-while is preferred
when we want to iterate through the loop till a certain condition is being evaluated to be true,
whereas for loop is used when we know exactly how many times our loop is going to run.
● Jump statements are used to manipulate the flow of a program when encountered. In C++, we mainly
have 4 types of jump statements: break, continue, goto, and exit().
● In C++, value 0 is evaluated as false and value 1 is evaluated as true.

● Logical operators are used to combine and check even more complex conditions in our program. In C++
we have three logical operators: &&, ||, !.
● Ternary operator can be used for a quick selection check in our program. Syntax : condition ? statements
if true: statements if false.
Functions in C++
∙ Read

∙ Discuss

∙ Courses
∙ Practice

∙ Video

A function is a set of statements that takes input, does some specific computation, and produces output.
The idea is to put some commonly or repeatedly done tasks together to make a function so that instead
of writing the same code again and again for different inputs, we can call this function.
In simple terms, a function is a block of code that runs only when it is called.
Syntax:

Syntax of Function

Example:

● C++

// C++ Program to demonstrate working of a


function
#include <iostream>
using namespace std;

// Following function that takes two


parameters 'x' and 'y'
// as input and returns max of two input
numbers
int max(int x, int y)
{
if (x > y)
return x;
else
return y;
}

// main function that doesn't receive any


parameter and
// returns integer
int main()
{
int a = 10, b = 20;

// Calling above function to find max of


'a' and 'b'
int m = max(a, b);

cout << "m is " << m;


return 0;
}

Output
m is 20
Time complexity: O(1)
Space complexity: O(1)
Why Do We Need Functions?
Functions help us in reducing code redundancy. If functionality is performed at multiple places in software, then
rather than writing the same code, again and again, we create a function and call it everywhere. This also helps
in maintenance as we have to make changes in only one place if we make changes to the functionality in future.
Functions make code modular. Consider a big file having many lines of code. It becomes really simple to read
and use the code, if the code is divided into functions.
Functions provide abstraction. For example, we can use library functions without worrying about their internal
work.
Function Declaration
A function declaration tells the compiler about the number of parameters, data types of parameters, and
returns type of function. Writing parameter names in the function declaration is optional but it is necessary
to put them in the definition. Below is an example of function declarations. (parameter names are not
present in the below declarations)

Function Declaration

Example:

● C++
// C++ Program to show function
that takes
// two integers as parameters
and returns
// an integer
int max(int, int);

// A function that takes an int


// pointer and an int variable
// as parameters and returns
// a pointer of type int
int* swap(int*, int);

// A function that takes


// a char as parameter and
// returns a reference variable
char* call(char b);

// A function that takes a


// char and an int as
parameters
// and returns an integer
int fun(char, int);

Types of Functions

Types of Function in C++

User Defined Function

User-defined functions are user/customer-defined blocks of code specially customized to reduce the
complexity of big programs. They are also commonly known as “tailor-made functions” which are built
only to satisfy the condition in which the user is facing issues meanwhile reducing the complexity of the
whole program.

Library Function

Library functions are also called “built-in Functions“. These functions are part of a compiler package that
is already defined and consists of a special function with special and different meanings. Built-in Function
gives us an edge as we can directly use them without defining them whereas in the user-defined function
we have to declare and define a function before using them.
For Example: sqrt(), setw(), strcat(), etc.

Parameter Passing to Functions


The parameters passed to the function are called actual parameters. For example, in the program
below, 5 and 10 are actual parameters.
The parameters received by the function are called formal parameters. For example, in the above
program x and y are formal parameters.

Formal Parameter and Actual Parameter

There are two most popular ways to pass parameters:


1. Pass by Value: In this parameter passing method, values of actual parameters are copied to the
function’s formal parameters. The actual and formal parameters are stored in different memory
locations so any changes made in the functions are not reflected in the actual parameters of the caller.

2. Pass by Reference: Both actual and formal parameters refer to the same locations, so any changes
made inside the function are reflected in the actual parameters of the caller.

Function Definition
Pass by value is used where the value of x is not modified using the function fun().

● C++

// C++ Program to demonstrate


function definition
#include <iostream>
using namespace std;

void fun(int x)
{
// definition of
// function
x = 30;
}

int main()
{
int x = 20;
fun(x);
cout << "x = " << x;
return 0;
}
Output
x = 20
Time complexity: O(1)
Space complexity: O(1)

Functions Using Pointers


The function fun() expects a pointer ptr to an integer (or an address of an integer). It modifies the value at
the address ptr. The dereference operator * is used to access the value at an address. In the statement
‘*ptr = 30’, the value at address ptr is changed to 30. The address operator & is used to get the address of
a variable of any data type. In the function call statement ‘fun(&x)’, the address of x is passed so that x
can be modified using its address.

● C++

// C++ Program to demonstrate


working of
// function using pointers
#include <iostream>
using namespace std;

void fun(int* ptr) { *ptr =


30; }

int main()
{
int x = 20;
fun(&x);
cout << "x = " << x;

return 0;
}
Output
x = 30
Time complexity: O(1)
Space complexity: O(1)

Difference between call by value and call by reference in C++


Call by value Call by reference

A copy of the value is passed to the An address of value is passed to the


function function

Changes made inside the function are Changes made inside the function are
not reflected
reflected on other functions outside the function as well

Actual and formal arguments will be Actual and formal arguments will be
created at created at
different memory location same memory location.
Functions in C++
1. Most C++ program has a function called main() that is called by the operating system when a user runs the
program.
2. Every function has a return type. If a function doesn’t return any value, then void is used as a return type.
Moreover, if the return type of the function is void, we still can use the return statement in the body of the
function definition by not specifying any constant, variable, etc. with it, by only mentioning the ‘return;’
statement which would symbolize the termination of the function as shown below:
C++
void function name(int a)
{
....... // Function Body
return; // Function execution would get terminated
}

3. To declare a function that can only be called without any parameter, we should use “void fun(void)“.
As a side note, in C++, an empty list means a function can only be called without any parameter. In C++,
both void fun() and void fun(void) are same.

Main Function
The main function is a special function. Every C++ program must contain a function named
main. It serves as the entry point for the program. The computer will start running the code
from the beginning of the main function.
Types of Main Functions
1. Without parameters:
● CPP

// Without Parameters
int main() { ...
return 0; }

2. With parameters:
● CPP
// With Parameters
int main(int argc, char* const argv[])
{ ... return 0; }

The reason for having the parameter option for the main function is to allow input from the command line.
When you use the main function with parameters, it saves every group of characters (separated by a space) after
the program name as elements in an array named argv.
Since the main function has the return type of int, the programmer must always have a return statement in the
code. The number that is returned is used to inform the calling program what the result of the program’s
execution was. Returning 0 signals that there were no problems.
C++ 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.
Syntax:
● C++

recursionfunction()
{
recursionfunction(); // calling
self function
}

To know more see this article.

C++ Passing Array to Function


In C++, to reuse the array logic, we can create a function. To pass an array to a function in C++,
we need to provide only the array name.
function_name(array_name[]); //passing array to function
Example: Print the minimum number in the given array.
● C++

#include <iostream>
using namespace std;
void printMin(int arr[5]);
int main()
{
int ar[5] = { 30, 10, 20, 40,
50 };
printMin(ar); // passing array to
function
}
void printMin(int arr[5])
{
int min = arr[0];
for (int i = 0; i < 5; i++) {
if (min > arr[i]) {
min = arr[i];
}
}
cout << "Minimum element is: " <<
min << "\n";
}

// Code submitted by Susobhan Akhuli

Output
Minimum element is: 10
Time complexity: O(n) where n is the size of the array
Space complexity: O(n) where n is the size of the array.
C++ Overloading (Function)
If we create two or more members having the same name but different in number or type of
parameters, it is known as C++ overloading. In C++, we can overload:
methods,
✔ constructors and

✔ indexed properties
Types of overloading in C++ are:
● Function overloading

● Operator overloading

● C++ Function Overloading


Function Overloading is defined as the process of having two or more functions with the same
name, but different parameters. In function overloading, the function is redefined by using
either different types or number of arguments. It is only through these differences a compiler
can differentiate between the functions.
The advantage of Function overloading is that it increases the readability of the program
because you don’t need to use different names for the same action.
Example: changing number of arguments of add() method
● C++

// program of function overloading when


number of arguments
// vary
#include <iostream>
using namespace std;
class Cal {
public:
static int add(int a, int b) { return a
+ b; }
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void)
{
Cal C; // class object declaration.
cout << C.add(10, 20) << endl;
cout << C.add(12, 20, 23);
return 0;
}

// Code Submitted By Susobhan Akhuli


Output
30
55
Time complexity: O(1)
Space complexity: O(1)
Example: when the type of the arguments vary.

● C++

// Program of function overloading with


different types of
// arguments.
#include <iostream>
using namespace std;
int mul(int, int);
float mul(float, int);

int mul(int a, int b) { return a * b; }


float mul(double x, int y) { return x * y; }
int main()
{
int r1 = mul(6, 7);
float r2 = mul(0.2, 3);
cout << "r1 is : " << r1 << endl;
cout << "r2 is : " << r2 << endl;
return 0;
}

// Code Submitted By Susobhan Akhuli

Output
r1 is : 42
r2 is : 0.6
Time Complexity: O(1)
Space Complexity: O(1)
Function Overloading and Ambiguity
When the compiler is unable to decide which function is to be invoked among the overloaded
function, this situation is known as function overloading ambiguity.
When the compiler shows the ambiguity error, the compiler does not run the program.

Causes of Ambiguity:
Type Conversion.
Function with default arguments.
Function with pass-by-reference.

Type Conversion:-
● C++

#include <iostream>
using namespace std;
void fun(int);
void fun(float);
void fun(int i) { cout << "Value of i is : "
<< i << endl; }
void fun(float j)
{
cout << "Value of j is : " << j << endl;
}
int main()
{
fun(12);
fun(1.2);
return 0;
}

// Code Submitted By Susobhan Akhuli

The above example shows an error “call of overloaded ‘fun(double)’ is ambiguous“. The fun(10) will call
the first function. The fun(1.2) calls the second function according to our prediction. But, this does not refer
to any function as in C++, all the floating point constants are treated as double not as a float. If we replace
float to double, the program works. Therefore, this is a type conversion from float to double.
Function with Default Arguments:-

● C++

#include <iostream>
using namespace std;
void fun(int);
void fun(int, int);
void fun(int i) { cout << "Value of i is : "
<< i << endl; }
void fun(int a, int b = 9)
{
cout << "Value of a is : " << a << endl;
cout << "Value of b is : " << b << endl;
}
int main()
{
fun(12);

return 0;
}

// Code Submitted By Susobhan Akhuli

The above example shows an error “call of overloaded ‘fun(int)’ is ambiguous“. The fun(int a,
int b=9) can be called in two ways: first is by calling the function with one argument, i.e.,
fun(12) and another way is calling the function with two arguments, i.e., fun(4,5). The fun(int i)
function is invoked with one argument. Therefore, the compiler could not be able to select
among fun(int i) and fun(int a,int b=9).

Function with Pass By Reference:-


● C++

#include <iostream>
using namespace std;
void fun(int);
void fun(int&);
int main()
{
int a = 10;
fun(a); // error, which fun()?
return 0;
}
void fun(int x) { cout << "Value of x is : "
<< x << endl; }
void fun(int& b)
{
cout << "Value of b is : " << b << endl;
}

// Code Submitted By Susobhan Akhuli

Friend Function
A friend function is a special function in C++ which in spite of not being a member
function of a class has the privilege to access private and protected data of a class.
A friend function is a non-member function or an ordinary function of a class, which is
declared by using the keyword “friend” inside the class. By declaring a function as a
friend, all the access permissions are given to the function.
The keyword “friend” is placed only in the function declaration but not in the function
definition.
When the friend function is called neither the name of the object nor the dot operator is
used. However, it may accept the object as an argument whose value it wants to access.
A friend function can be declared in any section of the class i.e. public, private, or
protected.
Declaration of friend function in C++
Syntax:
class <class_name> {
friend <return_type> <function_name>(argument/s);
};
Example_1: Find the largest of two numbers using Friend Function
C++
#include <iostream>
using namespace std;
class Largest {
int a, b, m;

public:
void set_data();
friend void
find_max(Largest);
};

void Largest::set_data()
{
cout << "Enter the first
number : ";
cin >> a;
cout << "\nEnter the
second number : ";
cin >> b;
}

void find_max(Largest t)
{
if (t.a > t.b)
t.m = t.a;
else
t.m = t.b;

cout << "\nLargest


number is " << t.m;
}

int main()
{
Largest l;
l.set_data();
find_max(l);
return 0;
}
Output
Enter the first number : 789
Enter the second number : 982
Largest number is 982
UNIT - IV

Classes and Objects –Constructors and Destructors –operators overloading –Type


Conversion- Inheritance – Pointers and Arrays.

C++ Object and Class


Since C++ is an object-oriented language, program is designed using objects and classes in C++.

C++ Object
In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.
In other words, object is an entity that has state and behavior. Here, state means data and behavior means
functionality.
Object is a runtime entity, it is created at runtime.
Object is an instance of a class. All the members of the class can be accessed through object.
Let's see an example to create object of student class using s1 as the reference variable.

Student s1; //creating an object of Student


In this example, Student is the type and s1 is the reference variable that refers to the instance of Student
class.

C++ Class
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.

class Student
{
public:
int id; //field or data member
float salary; //field or data member
String name;//field or data member
}

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.

#include <iostream>
using namespace std;
class Student {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
};
int main() {
Student s1; //creating an object of Student
s1.id = 201;
s1.name = "Sonoo Jaiswal";
cout<<s1.id<<endl;
cout<<s1.name<<endl;
return 0;
}
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.

#include <iostream>
using namespace std;
class Student {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
void insert(int i, string n)
{
id = i;
name = n;
}
void display()
{
cout<<id<<" "<<name<<endl;
}
};
int main(void) {
Student s1; //creating an object of Student
Student s2; //creating an object of Student
s1.insert(201, "Sonoo");
s2.insert(202, "Nakul");
s1.display();
s2.display();
return 0;
}
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.

#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
void insert(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
e1.insert(201, "Sonoo",990000);
e2.insert(202, "Nakul", 29000);
e1.display();
e2.display();
return 0;
}
Output:
201 Sonoo 990000
202 Nakul 29000

C++ Constructor
In C++, constructor is a special method which is invoked automatically at the time of object creation. It is
used to initialize the data members of new object generally. The constructor in C++ has the same name as
class or structure.
In brief, A particular procedure called a constructor is called automatically when an object is created in C+
+. In general, it is employed to create the data members of new things. In C++, the class or structure name
also serves as the constructor name. When an object is completed, the constructor is called. Because it
creates the values or gives data for the thing, it is known as a constructor.
The Constructors prototype looks like this:

<class-name> (list-of-parameters);
The following syntax is used to define the class's constructor:

<class-name> (list-of-parameters) { // constructor definition }


The following syntax is used to define a constructor outside of a class:

<class-name>: :<class-name> (list-of-parameters){ // constructor definition}


Constructors lack a return type since they don't have a return value.
There can be two types of constructors in C++.
Default constructor
Parameterized constructor
C++ Default Constructor
A constructor which has no argument is known as default constructor. It is invoked at the time of creating
object.
Let's see the simple example of C++ default Constructor.

#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}
Output:
Default Constructor Invoked
Default Constructor Invoked
C++ Parameterized Constructor
A constructor which has parameters is called parameterized constructor. It is used to provide different
values to distinct objects.
Let's see the simple example of C++ Parameterized Constructor.

#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
Output:
101 Sonoo 890000
102 Nakul 59000
What distinguishes constructors from a typical member function?
Constructor's name is the same as the class's
Default There isn't an input argument for constructors. However, input arguments are available for copy and
parameterized constructors.
There is no return type for constructors.
An object's constructor is invoked automatically upon creation.
It must be shown in the classroom's open area.
The C++ compiler creates a default constructor for the object if a constructor is not specified (expects any
parameters and has an empty body).
By using a practical example, let's learn about the various constructor types in C++. Imagine you visited a
store to purchase a marker. What are your alternatives if you want to buy a marker? For the first one, you
ask a store to give you a marker, given that you didn't specify the brand name or colour of the marker you
wanted, simply asking for one amount to a request. So, when we just said, "I just need a marker," he would
hand us whatever the most popular marker was in the market or his store. The default constructor is exactly
what it sounds like! The second approach is to go into a store and specify that you want a red marker of the
XYZ brand. He will give you that marker since you have brought up the subject. The parameters have been
set in this instance thus. And a parameterized constructor is exactly what it sounds like! The third one
requires you to visit a store and declare that you want a marker that looks like this (a physical marker on
your hand). The shopkeeper will thus notice that marker. He will provide you with a new marker when you
say all right. Therefore, make a copy of that marker. And that is what a copy constructor does!
What are the characteristics of a constructor?
The constructor has the same name as the class it belongs to.
Although it is possible, constructors are typically declared in the class's public section. However, this is not
a must.
Because constructors don't return values, they lack a return type.
When we create a class object, the constructor is immediately invoked.
Overloaded constructors are possible.
Declaring a constructor virtual is not permitted.
One cannot inherit a constructor.
Constructor addresses cannot be referenced to.
When allocating memory, the constructor makes implicit calls to the new and delete operators.
What is a copy constructor?
A member function known as a copy constructor initializes an item using another object from the same
class-an in-depth discussion on Copy Constructors.
Every time we specify one or more non-default constructors (with parameters) for a class, we also need to
include a default constructor (without parameters), as the compiler won't supply one in this circumstance.
The best practice is to always declare a default constructor, even though it is not required.
A reference to an object belonging to the same class is required by the copy constructor.

Sample(Sample &t)
{
id=t.id;
}
What is a destructor in C++?
An equivalent special member function to a constructor is a destructor. The constructor creates class objects,
which are destroyed by the destructor. The word "destructor," followed by the tilde () symbol, is the same as
the class name. You can only define one destructor at a time. One method of destroying an object made by a
constructor is to use a destructor. Destructors cannot be overloaded as a result. Destructors don't take any
arguments and don't give anything back. As soon as the item leaves the scope, it is immediately called.
Destructors free up the memory used by the objects the constructor generated. Destructor reverses the
process of creating things by destroying them.
The language used to define the class's destructor

~ <class-name>()
{
}
The language used to define the class's destructor outside of it
<class-name>: : ~ <class-name>(){}

C++ Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can be defined only once in
a class. Like constructors, it is invoked automatically.
A destructor is defined like constructor. It must have same name as class. But it is prefixed with a tilde sign
(~).

Note: C++ destructor cannot have parameters. Moreover, modifiers can't be applied on destructors.

C++ Constructor and Destructor Example


Let's see an example of constructor and destructor in C++ which is called automatically.

#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}
Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
What is operator overloading in C++?
Operators for user-defined classes can be made to function in C++. This indicates that the operator
overloading feature of C++ allows it to give the operators a special meaning specific to a data type. As an
illustration, we can overload the operator "+" in a class like "String" such that we can append two strings
with simply the letter "+." The classes Big Integer, Complex Numbers, and Fractional Numbers are a few
others where mathematical operators may be overloaded.
Compile-time polymorphisms include operator overloading. It is the concept of providing an existing C++
operator with additional meaning while maintaining its original meaning.
Example:

int x;
float y, sum;
sum=x+y;
The variables "x" and "y" in this example are of the built-in data types "int" and "float." The contents of "x"
and "y" can thus be added simply using the addition operator "+." Because only variables with built-in data
types are predefined to be added by the addition operator "+," this is the case.
Now, consider another example

class B
{
};
int main()
{
B b1,b2,b3;
b3= b1 + b2;
return 0;
}
Three variables of type "class B" are used in this example: "b1," "b2," and "b3." Using the "+" operator, we
are attempting to combine two objects, "b1" and "b2," that are of a user-defined type, or type "class B." This
is prohibited because the addition operator "+" can only operate on built-in data types by default. However,
since "class B" is a user-defined type, in this case, the compiler produces an error. In this situation, the idea
of "Operator overloading" is relevant.
The "+" operator must now be redefined so that it produces two class objects if the user desires it to add two
class objects. Utilizing the idea of "operator overloading," this is accomplished. Thus, the primary principle
of "Operator Overloading" is to employ C++ operators with class variables or class objects. Operators'
original meaning is not really altered by redefining them; rather, they have been given new meanings in
addition to their previous ones.

#include <iostream>
using namespace std;
class Count {
private:
int value;
public:
Count() : value(5) {}
void operator ++ () {
++value;
}
void display() {
cout << "Count: " << value << endl;
}
};
int main() {
Count count1;
++count1;
count1.display();
return 0;
}
Output:
Count: 6
What distinguishes operator functions from regular functions?
The same rules apply for operator functions as for regular functions. The main distinctions are that an
operator function's name always consists of the operator keyword headed by the operator symbol and that
operator functions are called whenever the associated operator is used.
Why below operators are not overloaded?
1) typeid - This gives a CPP application the ability to retrieve the true derived type of the object that a
pointer or reference is referring to. The sole purpose of this operator is to identify a type in a unique way.
Polymorphism can be used to make a user-defined type "appear" like another type, but it is crucial that the
typeid operator's meaning not be changed as otherwise grave problems may result.
2) sizeof - This gives the operand's (the object or data type entered) size. The compiler evaluates this; it
cannot be evaluated at runtime. The sizeof operation is implicitly used for appropriate pointer
incrementation in an array of objects. By changing its meaning through overloading, a foundational aspect
of the language would be destroyed.
3) Scope resolution (::) - By providing a namespace, aids in locating and defining the area to which an
identifier corresponds. It operates on names instead of values and is entirely assessed at runtime. If CPP
were overloaded, there is no syntax for capturing the operands of scope resolution because they are not
operations with data types. Therefore, overloading this operator is illogical from a syntax perspective.
Important information on operator overload
At least one of the operands must to be a user-defined class object in order for operator overloading to
function.
Assignment Operator: Every class has an automatic default assignment operator created by the compiler.
Most of the time, the default assignment operator is enough because it does assign all right-side members to
the left side (this behavior is the same as the copy constructor).
Any constructor that accepts a single argument and functions as a conversion constructor can be used to
perform indirect conversion to the class being created.
Type Conversion in C++
In this topic, we will discuss the conversion of one data type into another in the C++ programming
language. Type conversion is the process that converts the predefined data type of one variable into an
appropriate data type. The main idea behind type conversion is to convert two different data type variables
into a single data type to solve mathematical and logical expressions easily without any data loss.
For example, we are adding two numbers, where one variable is of int type and another of float type; we
need to convert or typecast the int variable into a float to make them both float data types to add them.
Type conversion can be done in two ways in C++, one is implicit type conversion, and the second
is explicit type conversion. Those conversions are done by the compiler itself, called the implicit type or
automatic type conversion. The conversion, which is done by the user or requires user interferences called
the explicit or user define type conversion. Let's discuss the implicit and explicit type conversion in C++.
Implicit Type Conversion
The implicit type conversion is the type of conversion done automatically by the compiler without any
human effort. It means an implicit conversion automatically converts one data type into another type based
on some predefined rules of the C++ compiler. Hence, it is also known as the automatic type conversion.
For example:

int x = 20;
short int y = 5;
int z = x + y;
In the above example, there are two different data type variables, x, and y, where x is an int type, and the y
is of short int data type. And the resultant variable z is also an integer type that stores x and y variables. But
the C++ compiler automatically converts the lower rank data type (short int) value into higher type (int)
before resulting the sum of two numbers. Thus, it avoids the data loss, overflow, or sign loss in implicit type
conversion of C++.
Order of the typecast in implicit conversion
The following is the correct order of data types from lower rank to higher rank:

bool -> char -> short int -> int -> unsigned int -> long int -> unsigned long int -> long long int -> float -
> double -> long double
Program to convert int to float type using implicit type conversion
Let's create a program to convert smaller rank data types into higher types using implicit type conversion.
Program1.cpp

#include <iostream>
using namespace std;
int main ()
{
// assign the integer value
int num1 = 25;
// declare a float variable
float num2;
// convert int value into float variable using implicit conversion
num2 = num1;
cout << " The value of num1 is: " << num1 << endl;
cout << " The value of num2 is: " << num2 << endl;
return 0;
}
Output
The value of num1 is: 25
The value of num2 is: 25
Program to convert double to int data type using implicit type conversion
Let's create a program to convert the higher data type into lower type using implicit type conversion.
Program2.cpp

#include <iostream>
using namespace std;
int main()
{
int num; // declare int type variable
double num2 = 15.25; // declare and assign the double variable

// use implicit type conversion to assign a double value to int variable


num = num2;
cout << " The value of the int variable is: " << num << endl;
cout << " The value of the double variable is: " << num2 << endl;
return 0;
}
Output
The value of the int variable is: 15
The value of the double variable is: 15.25
In the above program, we have declared num as an integer type and num2 as the double data type variable
and then assigned num2 as 15.25. After this, we assign num2 value to num variable using the assignment
operator. So, a C++ compiler automatically converts the double data value to the integer type before
assigning it to the num variable and print the truncate value as 15.
Explicit type conversion
Conversions that require user intervention to change the data type of one variable to another, is called
the explicit type conversion. In other words, an explicit conversion allows the programmer to manually
changes or typecasts the data type from one variable to another type. Hence, it is also known as typecasting.
Generally, we force the explicit type conversion to convert data from one type to another because it does not
follow the implicit conversion rule.
The explicit type conversion is divided into two ways:
Explicit conversion using the cast operator
Explicit conversion using the assignment operator
Program to convert float value into int type using the cast operator
Cast operator: In C++ language, a cast operator is a unary operator who forcefully converts one type into
another type.
Let's consider an example to convert the float data type into int type using the cast operator of the explicit
conversion in C++ language.
Program3.cpp

#include <iostream>
using namespace std;
int main ()
{
float f2 = 6.7;
// use cast operator to convert data from one type to another
int x = static_cast <int> (f2);
cout << " The value of x is: " << x;
return 0;
}
Output
The value of x is: 6
Program to convert one data type into another using the assignment operator
Let's consider an example to convert the data type of one variable into another using the assignment
operator in the C++ program.
Program4.cpp

#include <iostream>
using namespace std;
int main ()
{
// declare a float variable
float num2;
// initialize an int variable
int num1 = 25;

// convert data type from int to float


num2 = (float) num1;
cout << " The value of int num1 is: " << num1 << endl;
cout << " The value of float num2 is: " << num2 << endl;
return 0;
}
Output
The value of int num1 is: 25
The value of float num2 is: 25.0

C++ 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:
Single inheritance
Multiple inheritance
Hierarchical inheritance
Multilevel inheritance
Hybrid inheritance

Derived Classes
A Derived class is defined as the class derived from the base class.
The Syntax of Derived class:

class derived_class_name :: visibility-mode base_class_name


{
// body of the derived class.
}
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.
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.
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:
In C++, the default mode of visibility is private.
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.

#include <iostream>
using namespace std;
class Account {
public:
float salary = 60000;
};
class Programmer: public Account {
public:
float bonus = 5000;
};
int main(void) {
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
return 0;
}
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.

#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking...";
}
};
int main(void) {
Dog d1;
d1.eat();
d1.bark();
return 0;
}
Output:
Eating...
Barking...
Let's see a simple example.

#include <iostream>
using namespace std;
class A
{
int a = 4;
int b = 5;
public:
int mul()
{
int c = a*b;
return c;
}
};

class B : private A
{
public:
void display()
{
int result = mul();
std::cout <<"Multiplication of a and b is : "<<result<< std::endl;
}
};
int main()
{
B b;
b.display();

return 0;
}
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:

Public: When the member is declared as public, it is accessible to all the functions of the program.
Private: When the member is declared as private, it is accessible within the class only.
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

Public Private Protected

Private Not Inherited Not Inherited Not Inherited


Protected Protected Private Protected
Public Public Private Protected

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

#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking..."<<endl;
}
};
class BabyDog: public Dog
{
public:
void weep() {
cout<<"Weeping...";
}
};
int main(void) {
BabyDog d1;
d1.eat();
d1.bark();
d1.weep();
return 0;
}
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.

Syntax of the Derived class:

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


{
// Body of the class;
}
Let's see a simple example of multiple inheritance.

#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a(int n)
{
a = n;
}
};

class B
{
protected:
int b;
public:
void get_b(int n)
{
b = n;
}
};
class C : public A,public B
{
public:
void display()
{
std::cout << "The value of a is : " <<a<< std::endl;
std::cout << "The value of b is : " <<b<< std::endl;
cout<<"Addition of a and b is : "<<a+b;
}
};
int main()
{
C c;
c.get_a(10);
c.get_b(20);
c.display();

return 0;
}
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:

#include <iostream>
using namespace std;
class A
{
public:
void display()
{
std::cout << "Class A" << std::endl;
}
};
class B
{
public:
void display()
{
std::cout << "Class B" << std::endl;
}
};
class C : public A, public B
{
void view()
{
display();
}
};
int main()
{
C c;
c.display();
return 0;
}
Output:
error: reference to 'display' is ambiguous
display();
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:

class C : public A, public B


{
void view()
{
A :: display(); // Calling the display() function of class A.
B :: display(); // Calling the display() function of class B.

}
};
An ambiguity can also occur in single inheritance.
Consider the following situation:

class A
{
public:
void display()
{
cout<<?Class A?;
}
};
class B
{
public:
void display()
{
cout<<?Class B?;
}
};
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.

int main()
{
B b;
b.display(); // Calling the display() function of B class.
b.B :: display(); // Calling the display() function defined in B class.
}
C++ Hybrid Inheritance
Hybrid inheritance is a combination of more than one type of inheritance.
Let's see a simple example:

#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a()
{
std::cout << "Enter the value of 'a' : " << std::endl;
cin>>a;
}
};

class B : public A
{
protected:
int b;
public:
void get_b()
{
std::cout << "Enter the value of 'b' : " << std::endl;
cin>>b;
}
};
class C
{
protected:
int c;
public:
void get_c()
{
std::cout << "Enter the value of c is : " << std::endl;
cin>>c;
}
};

class D : public B, public C


{
protected:
int d;
public:
void mul()
{
get_a();
get_b();
get_c();
std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;
}
};
int main()
{
D d;
d.mul();
return 0;
}
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:

class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
Let's see a simple example:

#include <iostream>
using namespace std;
class Shape // Declaration of base class.
{
public:
int a;
int b;
void get_data(int n,int m)
{
a= n;
b = m;
}
};
class Rectangle : public Shape // inheriting Shape class
{
public:
int rect_area()
{
int result = a*b;
return result;
}
};
class Triangle : public Shape // inheriting Shape class
{
public:
int triangle_area()
{
float result = 0.5*a*b;
return result;
}
};
int main()
{
Rectangle r;
Triangle t;
int length,breadth,base,height;
std::cout << "Enter the length and breadth of a rectangle: " << std::endl;
cin>>length>>breadth;
r.get_data(length,breadth);
int m = r.rect_area();
std::cout << "Area of the rectangle is : " <<m<< std::endl;
std::cout << "Enter the base and height of the triangle: " << std::endl;
cin>>base>>height;
t.get_data(base,height);
float n = t.triangle_area();
std::cout <<"Area of the triangle is : " << n<<std::endl;
return 0;
}
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
C++ Array of Pointers
Array and pointers are closely related to each other. In C++, the name of an array is considered às a pointer,
i.e., the name of an array contains the address of an element. C++ considers the array name as the address of
the first element. For example, if we create an array, i.e., marks which hold the 20 values of integer type,
then marks will contain the address of first element, i.e., marks[0]. Therefore, we can say that array name
(marks) is a pointer which is holding the address of the first element of an array.
Let's understand this scenario through an example.

#include <iostream>
using namespace std;
int main()
{
int *ptr; // integer pointer declaration
int marks[10]; // marks array declaration
std::cout << "Enter the elements of an array :" << std::endl;
for(int i=0;i<10;i++)
{
cin>>marks[i];
}
ptr=marks; // both marks and ptr pointing to the same element..
std::cout << "The value of *ptr is :" <<*ptr<< std::endl;
std::cout << "The value of *marks is :" <<*marks<<std::endl;
}
In the above code, we declare an integer pointer and an array of integer type. We assign the address of
marks to the ptr by using the statement ptr=marks; it means that both the variables 'marks' and 'ptr' point to
the same element, i.e., marks[0]. When we try to print the values of *ptr and *marks, then it comes out to be
same. Hence, it is proved that the array name stores the address of the first element of an array.
Output

Array of Pointers
An array of pointers is an array that consists of variables of pointer type, which means that the variable is a
pointer addressing to some other element. Suppose we create an array of pointer holding 5 integer pointers;
then its declaration would look like:

int *ptr[5]; // array of 5 integer pointer.


In the above declaration, we declare an array of pointer named as ptr, and it allocates 5 integer pointers in
memory.
The element of an array of a pointer can also be initialized by assigning the address of some other element.
Let's observe this case through an example.

int a; // variable declaration.


ptr[2] = &a;
In the above code, we are assigning the address of 'a' variable to the third element of an array 'ptr'.
We can also retrieve the value of 'a' be dereferencing the pointer.

*ptr[2];
Let's understand through an example.

#include <iostream>
using namespace std;
int main()
{
int ptr1[5]; // integer array declaration
int *ptr2[5]; // integer array of pointer declaration
std::cout << "Enter five numbers :" << std::endl;
for(int i=0;i<5;i++)
{
std::cin >> ptr1[i];
}
for(int i=0;i<5;i++)
{
ptr2[i]=&ptr1[i];
}
// printing the values of ptr1 array
std::cout << "The values are" << std::endl;
for(int i=0;i<5;i++)
{
std::cout << *ptr2[i] << std::endl;
}
}
In the above code, we declare an array of integer type and an array of integer pointers. We have defined the
'for' loop, which iterates through the elements of an array 'ptr1', and on each iteration, the address of element
of ptr1 at index 'i' gets stored in the ptr2 at index 'i'.
Output

Till now, we have learnt the array of pointers to an integer. Now, we will see how to create the array of
pointers to strings.
Array of Pointer to Strings
An array of pointer to strings is an array of character pointers that holds the address of the first character of
a string or we can say the base address of a string.
The following are the differences between an array of pointers to string and two-dimensional array of
characters:
An array of pointers to string is more efficient than the two-dimensional array of characters in case of
memory consumption because an array of pointer to strings consumes less memory than the two-
dimensional array of characters to store the strings.
In an array of pointers, the manipulation of strings is comparatively easier than in the case of 2d array. We
can also easily change the position of the strings by using the pointers.
Let's see how to declare the array of pointers to string.
First, we declare the array of pointer to string:

char *names[5] = {"john",


"Peter",
"Marco",
"Devin",
"Ronan"};
In the above code, we declared an array of pointer names as 'names' of size 5. In the above case, we have
done the initialization at the time of declaration, so we do not need to mention the size of the array of a
pointer. The above code can be re-written as:

char *names[ ] = {"john",


"Peter",
"Marco",
"Devin",
"Ronan"};
In the above case, each element of the 'names' array is a string literal, and each string literal would hold the
base address of the first character of a string. For example, names[0] contains the base address of "john",
names[1] contains the base address of "Peter", and so on. It is not guaranteed that all the string literals will
be stored in the contiguous memory location, but the characters of a string literal are stored in a contiguous
memory location.
Let's create a simple example.

#include <iostream>
using namespace std;
int main()
{
char *names[5] = {"john",
"Peter",
"Marco",
"Devin",
"Ronan"};
for(int i=0;i<5;i++)
{
std::cout << names[i] << std::endl;
}
return 0;
}
In the above code, we have declared an array of char pointer holding 5 string literals, and the first character
of each string is holding the base address of the string.
Output

C++ Void Pointer


A void pointer is a general-purpose pointer that can hold the address of any data type, but it is not associated
with any data type.
Syntax of void pointer

void *ptr;
In C++, we cannot assign the address of a variable to the variable of a different data type. Consider the
following example:
int *ptr; // integer pointer declaration
float a=10.2; // floating variable initialization
ptr= &a; // This statement throws an error.
In the above example, we declare a pointer of type integer, i.e., ptr and a float variable, i.e., 'a'. After
declaration, we try to store the address of 'a' variable in 'ptr', but this is not possible in C++ as the variable
cannot hold the address of different data types.
Let's understand through a simple example.

#include <iostream.h>
using namespace std;
int main()
{
int *ptr;
float f=10.3;
ptr = &f; // error
std::cout << "The value of *ptr is : " <<*ptr<< std::endl;
return 0;
}
In the above program, we declare a pointer of integer type and variable of float type. An integer pointer
variable cannot point to the float variable, but it can point to an only integer variable.
Output

C++ has overcome the above problem by using the C++ void pointer as a void pointer can hold the address
of any data type.
Let's look at a simple example of void pointer.

#include <iostream>
using namespace std;
int main()
{
void *ptr; // void pointer declaration
int a=9; // integer variable initialization
ptr=&a; // storing the address of 'a' variable in a void pointer variable.
std::cout << &a << std::endl;
std::cout << ptr << std::endl;
return 0;
}
In the above program, we declare a void pointer variable and an integer variable where the void pointer
contains the address of an integer variable.
Output

Difference between void pointer in C and C++


In C, we can assign the void pointer to any other pointer type without any typecasting, whereas in C++, we
need to typecast when we assign the void pointer type to any other pointer type.
Let's understand through a simple example.
In C,

#include <stdio.h>
int main()
{
void *ptr; // void pointer declaration
int *ptr1; // integer pointer declaration
int a =90; // integer variable initialization
ptr=&a; // storing the address of 'a' in ptr
ptr1=ptr; // assigning void pointer to integer pointer type.
printf("The value of *ptr1 : %d",*ptr1);
return 0;
}
In the above program, we declare two pointers 'ptr' and 'ptr1' of type void and integer, respectively. We also
declare the integer type variable, i.e., 'a'. After declaration, we assign the address of 'a' variable to the pointer
'ptr'. Then, we assign the void pointer to the integer pointer, i.e., ptr1 without any typecasting because in C,
we do not need to typecast while assigning the void pointer to any other type of pointer.
Output

In C++,
#include <iostream>
using namespace std;
int main()
{
void *ptr; // void pointer declaration
int *ptr1; // integer pointer declaration
int data=10; // integer variable initialization
ptr=&data; // storing the address of data variable in void pointer variable
ptr1=(int *)ptr; // assigning void pointer to integer pointer
std::cout << "The value of *ptr1 is : " <<*ptr1<< std::endl;
return 0;
}
In the above program, we declare two pointer variables of type void and int type respectively. We also
create another integer type variable, i.e., 'data'. After declaration, we store the address of variable 'data' in a
void pointer variable, i.e., ptr. Now, we want to assign the void pointer to integer pointer, in order to do this,
we need to apply the cast operator, i.e., (int *) to the void pointer variable. This cast operator tells the
compiler which type of value void pointer is holding. For casting, we have to type the data type and * in a
bracket like (char *) or (int *).
Output

UNIT - V
POLYMORPHISM AND FILES

Memory Management Operators- Polymorphism – Virtual functions – Files – Exception


Handling – String Handling -Templates.
Memory management is a process of managing computer memory, assigning the memory space to the programs
to improve the overall system performance.
Memory Management Operators:
Why is memory management required?
As we know that arrays store the homogeneous data, so most of the time, memory is allocated to the array at the
declaration time. Sometimes the situation arises when the exact memory is not determined until runtime. To
avoid such a situation, we declare an array with a maximum size, but some memory will be unused. To avoid
the wastage of memory, we use the new operator to allocate the memory dynamically at the run time.
Memory Management Operators
In C language, we use the malloc() or calloc() functions to allocate the memory dynamically at run time, and
free() function is used to deallocate the dynamically allocated memory. C++ also supports these functions, but
C++ also defines unary operators such as new and delete to perform the same tasks, i.e., allocating and freeing
the memory.
New operator
A new operator is used to create the object while a delete operator is used to delete the object. When the object
is created by using the new operator, then the object will exist until we explicitly use the delete operator to
delete the object. Therefore, we can say that the lifetime of the object is not related to the block structure of the
program.
Syntax
pointer_variable = new data-type
The above syntax is used to create the object using the new operator. In the above syntax, 'pointer_variable' is
the name of the pointer variable, 'new' is the operator, and 'data-type' defines the type of the data.
Example 1:

int *p;
p = new int;
In the above example, 'p' is a pointer of type int.
Example 2:
float *q;
q = new float;
In the above example, 'q' is a pointer of type float.
In the above case, the declaration of pointers and their assignments are done separately. We can also combine
these two statements as follows:

int *p = new int;


float *q = new float;
Assigning a value to the newly created object
Two ways of assigning values to the newly created object:
We can assign the value to the newly created object by simply using the assignment operator. In the above case,
we have created two pointers 'p' and 'q' of type int and float, respectively. Now, we assign the values as follows:

*p = 45;
*q = 9.8;
We assign 45 to the newly created int object and 9.8 to the newly created float object.
We can also assign the values by using new operator which can be done as follows:

pointer_variable = new data-type(value);


Let's look at some examples.

int *p = new int(45);


float *p = new float(9.8);
How to create a single dimensional array
As we know that new operator is used to create memory space for any data-type or even user-defined data type
such as an array, structures, unions, etc., so the syntax for creating a one-dimensional array is given below:
pointer-variable = new data-type[size];
Examples:
int *a1 = new int[8];
In the above statement, we have created an array of type int having a size equal to 8 where p[0] refers first
element, p[1] refers the first element, and so on.
Delete operator
When memory is no longer required, then it needs to be deallocated so that the memory can be used for another
purpose. This can be achieved by using the delete operator, as shown below:

delete pointer_variable;
In the above statement, 'delete' is the operator used to delete the existing object, and 'pointer_variable' is the
name of the pointer variable.
In the previous case, we have created two pointers 'p' and 'q' by using the new operator, and can be deleted by
using the following statements:
delete p;
delete q;
The dynamically allocated array can also be removed from the memory space by using the following syntax:
delete [size] pointer_variable;
In the above statement, we need to specify the size that defines the number of elements that are required to be
freed. The drawback of this syntax is that we need to remember the size of the array. But, in recent versions of
C++, we do not need to mention the size as follows:
delete [ ] pointer_variable;
Let's understand through a simple example:
#include <iostream>
using namespace std
int main()
{
int size; // variable declaration
int *arr = new int[size]; // creating an array
cout<<"Enter the size of the array : ";
std::cin >> size; //
cout<<"\nEnter the element : ";
for(int i=0;i<size;i++) // for loop
{
cin>>arr[i];
}
cout<<"\nThe elements that you have entered are :";
for(int i=0;i<size;i++) // for loop
{
cout<<arr[i]<<",";
}
delete arr; // deleting an existing array.
return 0;
}
In the above code, we have created an array using the new operator. The above program will take the user input
for the size of an array at the run time. When the program completes all the operations, then it deletes the object
by using the statement delete arr.
Output

Advantages of the new operator


The following are the advantages of the new operator over malloc() function:
It does not use the sizeof() operator as it automatically computes the size of the data object.
It automatically returns the correct data type pointer, so it does not need to use the
typecasting.
Like other operators, the new and delete operator can also be overloaded.
It also allows you to initialize the data object while creating the memory space for the object
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++:
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.

class A // base class declaration.


{
int a;
public:
void display()
{
cout<< "Class A ";
}
};
class B : public A // derived class declaration.
{
int b;
public:
void display()
{
cout<<"Class B";
}
};
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.
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.

Compile time polymorphism Run time polymorphism

The function to be invoked is known at the The function to be invoked is known at the
compile time. run time.
It is also known as overloading, early binding and It is also known as overriding, Dynamic
static binding. binding and late binding.
Overloading is a compile time polymorphism Overriding is a run time polymorphism
where more than one method is having the same where more than one method is having the
name but with the different number of parameters same name, number of parameters and the
or the type of the parameters. type of the parameters.
It is achieved by function overloading and It is achieved by virtual functions and
operator overloading. pointers.
It provides fast execution as it is known at the It provides slow execution as it is known at
compile time. the run time.
It is less flexible as mainly all the things execute It is more flexible as all the things execute
at the compile time. 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.

#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{ cout<<"Eating bread...";
}
};
int main(void) {
Dog d = Dog();
d.eat();
return 0;
}
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.

#include <iostream>
using namespace std;
class Shape { // base class
public:
virtual void draw(){ // virtual function
cout<<"drawing..."<<endl;
}
};
class Rectangle: public Shape // inheriting Shape class.
{
public:
void draw()
{
cout<<"drawing rectangle..."<<endl;
}
};
class Circle: public Shape // inheriting Shape class.

{
public:
void draw()
{
cout<<"drawing circle..."<<endl;
}
};
int main(void) {
Shape *s; // base class pointer.
Shape sh; // base class object.
Rectangle rec;
Circle cir;
s=&sh;
s->draw();
s=&rec;
s->draw();
s=?
s->draw();
}
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.

#include <iostream>
using namespace std;
class Animal { // base class declaration.
public:
string color = "Black";
};
class Dog: public Animal // inheriting Animal class.
{
public:
string color = "Grey";
};
int main(void) {
Animal d= Dog();
cout<<d.color;
}
Output:
Black
C++ Overloading (Function and Operator)
If we create two or more members having the same name but different in number or type of parameter, it is
known as C++ overloading. In C++, we can overload:
methods,
constructors, and
indexed properties
It is because these members have parameters only.
Types of overloading in C++ are:
Function overloading
Operator overloading
C++ Function Overloading
Function Overloading is defined as the process of having two or more function with the same name, but
different in parameters is known as function overloading in C++. In function overloading, the function is
redefined by using either different types of arguments or a different number of arguments. It is only through
these differences compiler can differentiate between the functions.
The advantage of Function overloading is that it increases the readability of the program because you don't
need to use different names for the same action.
C++ Function Overloading Example
Let's see the simple example of function overloading where we are changing number of arguments of add()
method.
// program of function overloading when number of arguments vary.

#include <iostream>
using namespace std;
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
Output:
30
55
Let's see the simple example when the type of the arguments vary.
// Program of function overloading with different types of arguments.

#include<iostream>
using namespace std;
int mul(int,int);
float mul(float,int);

int mul(int a,int b)


{
return a*b;
}
float mul(double x, int y)
{
return x*y;
}
int main()
{
int r1 = mul(6,7);
float r2 = mul(0.2,3);
std::cout << "r1 is : " <<r1<< std::endl;
std::cout <<"r2 is : " <<r2<< std::endl;
return 0;
}
Output:
r1 is : 42
r2 is : 0.6
Function Overloading and Ambiguity
When the compiler is unable to decide which function is to be invoked among the overloaded function, this
situation is known as function overloading.
When the compiler shows the ambiguity error, the compiler does not run the program.
Causes of Function Overloading:
Type Conversion.
Function with default arguments.
Function with pass by reference.
Type Conversion:
Let's see a simple example.

#include<iostream>
using namespace std;
void fun(int);
void fun(float);
void fun(int i)
{
std::cout << "Value of i is : " <<i<< std::endl;
}
void fun(float j)
{
std::cout << "Value of j is : " <<j<< std::endl;
}
int main()
{
fun(12);
fun(1.2);
return 0;
}
The above example shows an error "call of overloaded 'fun(double)' is ambiguous". The fun(10) will call
the first function. The fun(1.2) calls the second function according to our prediction. But, this does not refer
to any function as in C++, all the floating point constants are treated as double not as a float. If we replace
float to double, the program works. Therefore, this is a type conversion from float to double.
Function with Default Arguments
Let's see a simple example.

#include<iostream>
using namespace std;
void fun(int);
void fun(int,int);
void fun(int i)
{
std::cout << "Value of i is : " <<i<< std::endl;
}
void fun(int a,int b=9)
{
std::cout << "Value of a is : " <<a<< std::endl;
std::cout << "Value of b is : " <<b<< std::endl;
}
int main()
{
fun(12);

return 0;
}
The above example shows an error "call of overloaded 'fun(int)' is ambiguous". The fun(int a, int b=9) can
be called in two ways: first is by calling the function with one argument, i.e., fun(12) and another way is
calling the function with two arguments, i.e., fun(4,5). The fun(int i) function is invoked with one argument.
Therefore, the compiler could not be able to select among fun(int i) and fun(int a,int b=9).
Function with pass by reference
Let's see a simple example.

#include <iostream>
using namespace std;
void fun(int);
void fun(int &);
int main()
{
int a=10;
fun(a); // error, which f()?
return 0;
}
void fun(int x)
{
std::cout << "Value of x is : " <<x<< std::endl;
}
void fun(int &b)
{
std::cout << "Value of b is : " <<b<< std::endl;
}
The above example shows an error "call of overloaded 'fun(int&)' is ambiguous". The first function takes
one integer argument and the second function takes a reference parameter as an argument. In this case, the
compiler does not know which function is needed by the user as there is no syntactical difference between
the fun(int) and fun(int &).
C++ Operators Overloading
Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the
special meaning to the user-defined data type. Operator overloading is used to overload or redefines most of
the operators available in C++. It is used to perform the operation on the user-defined data type. For
example, C++ provides the ability to add the variables of the user-defined data type that is applied to the
built-in data types.
The advantage of Operators overloading is to perform different operations on the same operand.
Operator that cannot be overloaded are as follows:
Scope operator (::)
Sizeof
member selector(.)
member pointer selector(*)
ternary operator(?:)
Syntax of Operator Overloading

return_type class_name : : operator op(argument_list)


{
// body of the function.
}
Where the return type is the type of value returned by the function.
class_name is the name of the class.
operator op is an operator function where op is the operator being overloaded, and the operator is the
keyword.
Rules for Operator Overloading
Existing operators can only be overloaded, but the new operators cannot be overloaded.
The overloaded operator contains atleast one operand of the user-defined data type.
We cannot use friend function to overload certain operators. However, the member function can be used to
overload those operators.
When unary operators are overloaded through a member function take no explicit arguments, but, if they are
overloaded by a friend function, takes one argument.
When binary operators are overloaded through a member function takes one explicit argument, and if they
are overloaded through a friend function takes two explicit arguments.
C++ Operators Overloading Example
Let's see the simple example of operator overloading in C++. In this example, void operator ++ () operator
function is defined (inside Test class).
// program to overload the unary operator ++.

#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++() {
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}
Output:
The Count is: 10
Let's see a simple example of overloading the binary operators.
// program to overload the binary operators.

#include <iostream>
using namespace std;
class A
{

int x;
public:
A(){}
A(int i)
{
x=i;
}
void operator+(A);
void display();
};

void A :: operator+(A a)
{

int m = x+a.x;
cout<<"The result of the addition of two objects is : "<<m;
}
int main()
{
A a1(5);
A a2(4);
a1+a2;
return 0;
}
Output:
The result of the addition of two objects is : 9

C++ Function Overriding


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.

#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
};
int main(void) {
Dog d = Dog();
d.eat();
return 0;
}
Output:
Eating bread…
C++ virtual function
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.
It is used to tell the compiler to perform dynamic linkage or late binding on the function.
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.
A 'virtual' is a keyword preceding the normal declaration of a function.
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


Virtual functions must be members of some class.
Virtual functions cannot be static members.
They are accessed through object pointers.
They can be a friend of another class.
A virtual function must be defined in the base class, even though it is not used.
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.
We cannot have a virtual constructor, but we can have a virtual destructor
Consider the situation when we don't use the virtual keyword.

#include <iostream>
using namespace std;
class A
{
int x=5;
public:
void display()
{
std::cout << "Value of x is : " << x<<std::endl;
}
};
class B: public A
{
int y = 10;
public:
void display()
{
std::cout << "Value of y is : " <<y<< std::endl;
}
};
int main()
{
A *a;
B b;
a = &b;
a->display();
return 0;
}
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 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.

#include <iostream>
{
public:
virtual void display()
{
cout << "Base class is invoked"<<endl;
}
};
class B:public A
{
public:
void display()
{
cout << "Derived Class is invoked"<<endl;
}
};
int main()
{
A* a; //pointer of base class
B b; //object of derived class
a = &b;
a->display(); //Late Binding occurs
}
Output:
Derived Class is invoked
Pure Virtual Function
A virtual function is not used for performing any task. It only serves as a placeholder.
When the function has no definition, such function is known as "do-nothing" function.
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.
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.
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:

virtual void display() = 0;


Let's see a simple example:

#include <iostream>
using namespace std;
class Base
{
public:
virtual void show() = 0;
};
class Derived : public Base
{
public:
void show()
{
std::cout << "Derived class is derived from the base class." << std::endl;
}
};
int main()
{
Base *bptr;
//Base b;
Derived d;
bptr = &d;
bptr->show();
return 0;
}
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.

C++ Files

C++ Files

The fstream library allows us to work with files.

To use the fstream library, include both the standard <iostream> AND the <fstream> header file:

Example

#include <iostream>
#include <fstream>

There are three classes included in the fstream library, which are used to create, write or read files:

Class Description
ofstream Creates and writes to files
ifstream Reads from files
fstream A combination of ofstream and ifstream: creates, reads, and writes to files

Create and Write To a File

To create a file, use either the ofstream or fstream class, and specify the name of the file.

To write to the file, use the insertion operator (<<).

Example

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

int main() {
// Create and open a text file
ofstream MyFile("filename.txt");

// Write to the file


MyFile << "Files can be tricky, but it is fun enough!";
// Close the file
MyFile.close();
}

Why do we close the file?

It is considered good practice, and it can clean up unnecessary memory space.

Read a File

To read from a file, use either the ifstream or fstream class, and the name of the file.

Note that we also use a while loop together with the getline() function (which belongs to the ifstream class)
to read the file line by line, and to print the content of the file:

Example

// Create a text string, which is used to output the text file


string myText;

// Read from the text file


ifstream MyReadFile("filename.txt");

// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}

// Close the file


MyReadFile.close();

C++ Files and Streams


In C++ programming we are using the iostream standard library, it provides cin and cout methods for
reading from input and writing to output respectively.
To read and write from a file we are using the standard C++ library called fstream. Let us see the data types
define in fstream library is:
Data Description
Type

fstream It is used to create files, write information to files, and read information from
files.
ifstream It is used to read information from files.
ofstream It is used to create files and write information to the files.

C++ FileStream example: writing to a file


Let's see the simple example of writing to a text file testout.txt using C++ FileStream programming.

#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream filestream("testout.txt");
if (filestream.is_open())
{
filestream << "Welcome to javaTpoint.\n";
filestream << "C++ Tutorial.\n";
filestream.close();
}
else cout <<"File opening is fail.";
return 0;
}
Output:
The content of a text file testout.txt is set with the data:
Welcome to javaTpoint.
C++ Tutorial.

C++ FileStream example: reading from a file


Let's see the simple example of reading from a text file testout.txt using C++ FileStream programming.

#include <iostream>
#include <fstream>
using namespace std;
int main () {
string srg;
ifstream filestream("testout.txt");
if (filestream.is_open())
{
while ( getline (filestream,srg) )
{
cout << srg <<endl;
}
filestream.close();
}
else {
cout << "File opening is fail."<<endl;
}
return 0;
}

Note: Before running the code a text file named as "testout.txt" is need to be created and the content
of a text file is given below:
Welcome to javaTpoint.
C++ Tutorial.

Output:
Welcome to javaTpoint.
C++ Tutorial.

C++ Read and Write Example


Let's see the simple example of writing the data to a text file testout.txt and then reading the data from the
file using C++ FileStream programming.

#include <fstream>
#include <iostream>
using namespace std;
int main () {
char input[75];
ofstream os;
os.open("testout.txt");
cout <<"Writing to a text file:" << endl;
cout << "Please Enter your name: ";
cin.getline(input, 100);
os << input << endl;
cout << "Please Enter your age: ";
cin >> input;
cin.ignore();
os << input << endl;
os.close();
ifstream is;
string line;
is.open("testout.txt");
cout << "Reading from a text file:" << endl;
while (getline (is,line))
{
cout << line << endl;
}
is.close();
return 0;
}
Output:
Writing to a text file:
Please Enter your name: Nakul Jain
Please Enter your age: 22
Reading from a text file: Nakul Jain
22

C++ Exception Handling


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

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:
C++ try/catch
In C++ programming, exception handling is performed using try/catch statement. The C++ try block is used
to place the code that may occur exception. The catch block is used to handle the exception.

C++ example without try/catch

#include <iostream>
using namespace std;
float division(int x, int y) {
return (x/y);
}
int main () {
int i = 50;
int j = 0;
float k = 0;
k = division(i, j);
cout << k << endl;
return 0;
}
Output:
Floating point exception (core dumped)

C++ try/catch example

#include <iostream>
using namespace std;
float division(int x, int y) {
if( y == 0 ) {
throw "Attempted to divide by zero!";
}
return (x/y);
}
int main () {
int i = 25;
int j = 0;
float k = 0;
try {
k = division(i, j);
cout << k << endl;
}catch (const char* e) {
cerr << e << endl;
}
return 0;
}
Output:
Attempted to divide by zero!
C++ Strings
In C++, string is an object of std::string class that represents sequence of characters. We can perform many
operations on strings such as concatenation, comparison, conversion etc.

C++ String Example


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

#include <iostream>
using namespace std;
int main( ) {
string s1 = "Hello";
char ch[] = { 'C', '+', '+'};
string s2 = string(ch);
cout<<s1<<endl;
cout<<s2<<endl;
}
Output:
Hello
C++

C++ String Compare Example


Let's see the simple example of string comparison using strcmp() function.

#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
char key[] = "mango";
char buffer[50];
do {
cout<<"What is my favourite fruit? ";
cin>>buffer;
} while (strcmp (key,buffer) != 0);
cout<<"Answer is correct!!"<<endl;
return 0;
}
Output:
What is my favourite fruit? apple
What is my favourite fruit? banana
What is my favourite fruit? mango
Answer is correct!!

C++ String Concat Example


Let's see the simple example of string concatenation using strcat() function.

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char key[25], buffer[25];
cout << "Enter the key string: ";
cin.getline(key, 25);
cout << "Enter the buffer string: ";
cin.getline(buffer, 25);
strcat(key, buffer);
cout << "Key = " << key << endl;
cout << "Buffer = " << buffer<<endl;
return 0;
}
Output:
Enter the key string: Welcome to
Enter the buffer string: C++ Programming.
Key = Welcome to C++ Programming.
Buffer = C++ Programming.

C++ String Copy Example


Let's see the simple example of copy the string using strcpy() function.

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char key[25], buffer[25];
cout << "Enter the key string: ";
cin.getline(key, 25);
strcpy(buffer, key);
cout << "Key = "<< key << endl;
cout << "Buffer = "<< buffer<<endl;
return 0;
}
Output:
Enter the key string: C++ Tutorial
Key = C++ Tutorial
Buffer = C++ Tutorial

C++ String Length Example


Let's see the simple example of finding the string length using strlen() function.

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char ary[] = "Welcome to C++ Programming";
cout << "Length of String = " << strlen(ary)<<endl;
return 0;
}
Output:
Length of String = 26
C++ String Functions

Function Description

int compare(const string& str) It is used to compare two string objects.


int length() It is used to find the length of the string.
void swap(string& str) It is used to swap the values of two string objects.
string substr(int pos,int n) It creates a new string object of n characters.
int size() It returns the length of the string in terms of bytes.
void resize(int n) It is used to resize the length of the string up to n
characters.
string& replace(int pos,int It replaces portion of the string that begins at character
len,string& str) position pos and spans len characters.
string& append(const string& str) It adds new characters at the end of another string object.
char& at(int pos) It is used to access an individual character at specified
position pos.
int find(string& str,int pos,int n) It is used to find the string specified in the parameter.
int find_first_of(string& str,int It is used to find the first occurrence of the specified
pos,int n) sequence.
int find_first_not_of(string& It is used to search the string for the first character that does
str,int pos,int n ) not match with any of the characters specified in the string.
int find_last_of(string& str,int It is used to search the string for the last character of
pos,int n) specified sequence.
int find_last_not_of(string& It searches for the last character that does not match with
str,int pos) the specified sequence.
string& insert() It inserts a new character before the character indicated by
the position pos.
int max_size() It finds the maximum length of the string.
void push_back(char ch) It adds a new character ch at the end of the string.
void pop_back() It removes a last character of the string.
string& assign() It assigns new value to the string.
int copy(string& str) It copies the contents of string into another.
char& back() It returns the reference of last character.
Iterator begin() It returns the reference of first character.
int capacity() It returns the allocated space for the string.
const_iterator cbegin() It points to the first element of the string.
const_iterator cend() It points to the last element of the string.
void clear() It removes all the elements from the string.
const_reverse_iterator crbegin() It points to the last character of the string.
const_char* data() It copies the characters of string into an array.
bool empty() It checks whether the string is empty or not.
string& erase() It removes the characters as specified.
char& front() It returns a reference of the first character.
string& operator+=() It appends a new character at the end of the string.
string& operator=() It assigns a new value to the string.
char operator[](pos) It retrieves a character at specified position pos.
int rfind() It searches for the last occurrence of the string.
iterator end() It references the last character of the string.
reverse_iterator rend() It points to the first character of the string.
void shrink_to_fit() It reduces the capacity and makes it equal to the size of the
string.
char* c_str() It returns pointer to an array that contains null terminated
sequence of characters.
const_reverse_iterator crend() It references the first character of the string.
reverse_iterator rbegin() It reference the last character of the string.
void reserve(inr len) It requests a change in capacity.
allocator_type get_allocator(); It returns the allocated object associated with the string.

C++ Templates
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:
Function templates
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
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.
The type of the data that the function will operate on depends on the type of the data passed as a parameter.
For example, Quick sorting algorithm is implemented using a generic function, it can be implemented to an
array of integers or array of floats.
A Generic function is created by using the keyword template. The template defines what function will do.
Syntax of Function Template

template < class Ttype> ret_type func_name(parameter_list)


{
// body of function.
}
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:

#include <iostream>
using namespace std;
template<class T> T add(T &a,T &b)
{
T result = a+b;
return result;

}
int main()
{
int i =2;
int j =3;
float m = 2.3;
float n = 1.2;
cout<<"Addition of i and j is :"<<add(i,j);
cout<<'\n';
cout<<"Addition of m and n is :"<<add(m,n);
return 0;
}
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

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


return_type function_name (arguments of type T1, T2....)
{
// body of function.
}
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:

#include <iostream>
using namespace std;
template<class X,class Y> void fun(X a,Y b)
{
std::cout << "Value of a is : " <<a<< std::endl;
std::cout << "Value of b is : " <<b<< std::endl;
}

int main()
{
fun(15,12.3);

return 0;
}
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:

#include <iostream>
using namespace std;
template<class X> void fun(X a)
{
std::cout << "Value of a is : " <<a<< std::endl;
}
template<class X,class Y> void fun(X b ,Y c)
{
std::cout << "Value of b is : " <<b<< std::endl;
std::cout << "Value of c is : " <<c<< std::endl;
}
int main()
{
fun(10);
fun(20,30.5);
return 0;
}
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.
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:

#include <iostream>
using namespace std;
void fun(double a)
{
cout<<"value of a is : "<<a<<'\n';
}
void fun(int b)
{
if(b%2==0)
{
cout<<"Number is even";
}
else
{
cout<<"Number is odd";
}

int main()
{
fun(4.6);
fun(6);
return 0;
}
Output:
value of a is : 4.6
Number is even
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

template<class Ttype>
class class_name
{
.
.
}
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

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:

#include <iostream>
using namespace std;
template<class T>
class A
{
public:
T num1 = 5;
T num2 = 6;
void add()
{
std::cout << "Addition of num1 and num2 : " << num1+num2<<std::endl;
}

};

int main()
{
A<int> d;
d.add();
return 0;
}
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

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


class class_name
{
// Body of the class.
}
Let's see a simple example when class template contains two generic data types.
#include <iostream>
using namespace std;
template<class T1, class T2>
class A
{
T1 a;
T2 b;
public:
A(T1 x,T2 y)
{
a = x;
b = y;
}
void display()
{
std::cout << "Values of a and b are : " << a<<" ,"<<b<<std::endl;
}
};

int main()
{
A<int,float> d(5,6.5);
d.display();
return 0;
}
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:

template<class T, int size>


class array
{
T arr[size]; // automatic array initialization.
};
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:

array<int, 15> t1; // array of 15 integers.


array<float, 10> t2; // array of 10 floats.
array<char, 4> t3; // array of 4 chars.
Let's see a simple example of nontype template arguments.

#include <iostream>
using namespace std;
template<class T, int size>
class A
{
public:
T arr[size];
void insert()
{
int i =1;
for (int j=0;j<size;j++)
{
arr[j] = i;
i++;
}
}

void display()
{
for(int i=0;i<size;i++)
{
std::cout << arr[i] << " ";
}
}
};
int main()
{
A<int,10> t1;
t1.insert();
t1.display();
return 0;
}
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
C++ supports a powerful feature known as a template to implement the concept of generic programming.
A template allows us to create a family of classes or family of functions to handle different data types.
Template classes and functions eliminate the code duplication of different data types and thus makes the
development easier and faster.
Multiple parameters can be used in both class and function template.
Template functions can also be overloaded.
We can also use nontype arguments such as built-in or derived data types as template arguments.

You might also like