[go: up one dir, main page]

0% found this document useful (0 votes)
27 views74 pages

Gaidakot Notes2

Uploaded by

abhinavkhadka0
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)
27 views74 pages

Gaidakot Notes2

Uploaded by

abhinavkhadka0
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/ 74

What is data structure?

- Data structure is a way of organizing all data items and establishing


relationship among those data items.
- Data structures are the building blocks of a program. Data structure
mainly specifies the following four things:
1. Organization of data.
2. Accessing methods
3. Degree of associativity
4. Processing alternatives for information
To develop a program of an algorithm, we should select an
appropriate data structure for that algorithm. Therefore algorithm and
its associated data structures form a program.
Algorithm + Data structure = Program
A static data structure is one whose capacity is fixed at creation. For
example, array.
A dynamic data structure is one whose capacity is variable, so it can
expand or contract at any time. For example, linked list, binary tree
etc.
Advantages of data structure
Given below are important advantages of data
structure:
 Data structure helps in efficient storage of data in
the storage device.
 Data structure usage provides convenience while
retrieving the data from storage device.
 Data structure provides effective and efficient
processing of small as well as large amount of
data.
 Usage of proper data structure, can help
programmer save lots of time or processing time
while operations such as storage, retrieval or
processing of data.
 Manipulation of large amount of data can be
carried out easily with the use of good data
structure approach.
 Most of the well organized data structures like
Array, stack, queues, graph, tree, linked list has
well built and pre-planned approach for operations
like storage, addition, retrieval, manipulation,
deletion, etc. While using them, programmer can
be completely rely on these data structures.
 Data structure usage can simply encourage
reusability in long run as well.
 Data structure like array, linked list, tree, graph,
stack, etc. are well tested and proven one so any
one can easily use them directly without need to
research and development on them. If you decide
to create your own data structure that may need
some research work but then it would definitely be
to solve something more complex than what these
can provide. Isn't it?
Advantages of Data Structures
 Data structure is a secure way of storing the data on our

system.
 Data structures help us to process the data easily.

 Data structures also help us to store the data on the disks

very efficiently so that we can easily retrieve the data.


 Data structures are very important for designing algorithms.

 As we know that data structures are a way to arrange data

into a certain form. Now the program execution speed is


highly dependent on the type of data structure used.
 Data structures provide us with the reusability of the data.

We can create some data in certain formats and store it in


libraries so that can be used by different clients.
 Data structures like Graphs help us to visualize, process, and

model real-life problems.


 Data structures like Trees help us to visualize, implement and

work with hierarchal data sets. For example, if the user has
searched a then he/she will search b, so it is widely used in
searching related fields.
 Data structures provide us with data abstraction so that the
user need not be worried about how the data is being stored
on the system.
 Data structures provided by various programming languages
come with various built-in functions (or methods) that help us
to utilize the particular database more efficiently.
 If a program is working with huge data sets, then the efficient
working of such a program depends widely on the type of data
structure used. So, an adequate selection of data structure is
very important.
 Data structures are also used in the database management
system (DBMS) field for creating an index, storing the data
using B and B+ trees, etc.
 Data structures have many practical uses such as dynamic
memory allocation, process scheduling, file system
organization, dictionary, etc.

Need of Data Structure

As applications are becoming more complex and the


amount of data is increasing day by day, which may
cause problems with processing speed, searching data,
handling multiple requests etc. Data structure provides
a way of organizing, managing, and storing data
efficiently. With the help of data structure, the data
items can be traversed easily. Data structure provides
efficiency, reusability and abstraction. It plays an
important role in enhancing the performance of a
program because the main function of the program is
to store and retrieve the user’s data as fast as possible.

Why do we need data structures?

Data structures are important for the following reasons:


1. Data structures are used in every program or
software system to arrange the data.
2. Data structures are essential ingredients of
many efficient algorithms. It helps in the
management of huge amounts of data, such as
a large integrated collection of databases.
3. Each Data Structure allows data/elements to be
stored in a specific manner in the memory.
4. Data Structure helps in efficient data search and
retrieval.
5. For specific problems, specific Data structures
are used.
6. Data Structure allows managing a large amount
of data, such as large databases and indexing
services such as a hash table.
7. Data structures organized the storage and
retrieval of data and information which is stored
in both main memory and secondary memory.

#Classification of Data Structure:

1.linear And @. Nonlinear


What Is Linear Data Structure?

A linear data structure is known as a data structure


that allows data elements to be arranged in a
sequential or linear fashion. Each element is attached
with its next and previous adjacent. A linear data
structure only has one level and performs linear
searching in the data structure. We can therefore
traverse all elements in a single run. Because
computer memory is linearly arranged, linear data
structures are simple to implement. Linear data
structure examples are array, linked list, stack, queue,
etc.

Characteristics of Linear Data Structure


This is a data structure in which the data arrangement
follows a linear trend. Each element in the data
structure is arranged in a linear fashion so that it can
be linked to the previous and next elements. The
elements are stored in a linear fashion, which allows
for single-level data storage. The data can be
accessed in one run.

 It's a data structure that stores and manages data


in a linear order.
 The data elements of the sequence are linked from
one to the next.
 Implementing the linear structure of data within a
computer's RAM is simple, provided that the data
are organized sequentially.
 Array, queue. Stack, linked list, etc., are a few
examples of such a structure.
 Only one relationship exists between the data
elements in the data structure.
 Because the data elements are stored on a single
level, it is possible to traverse the data elements in
one run.
 If a linear data storage structure is used, it is not
well utilized.
 The complexity of the structure's time increases
with an increase in its size.
Types in Linear Data Structure

The Array, Linked List, Stack, and Queue are all kinds
of linear data structure types. Let's look at each in
greater detail.

1. Array
An Array is a type of framework that stores
homogeneous parts in connected memory locations. It
is precisely the same kinds of objects that are saved
sequentially inside an array. The fundamental concept
behind linear arrays in the data structure is that
multiple pieces of data similar can be stored together.
Before saving the data in an array, it is essential that
the size of an array need to be established. Every
aspect of the array can be accessed or modified, and
the data is stored in an index to identify their places of
their own.

The concept of an array can be explained through an


easy example of saving the marks for all the students
in a class if you assume that there are twenty pupils.
The size of your array needs to be identified as 20.
The marks of all pupils could also be saved in the
array created without the need to create separate
variables for markings for every pupil. A simple
traversal of the array will allow access to the parts.

2. Linked List
It is this type of data system where individual objects
are stored sequentially. Each object within the system
has a reference and information for the next object.
The last node on the linked list has an identifier for
null.

The first element linked to the list is known as the


"mind" of the list. There are a lot of differences
between linked lists and other kinds of data structures.
This concerns the allocation of memory, the inside
structures of the structure, and the operation carried
out on this linked list.
Finding an element of a linked list is slow when
compared to arrays since the indexing of an array aids
in locating the element. The process in the case of a
linked list must begin in mind and work through the
whole structure until the component you want is
found. Contrary to this, the advantage of linked lists
would be that the addition or even the removal of
elements at the beginning is completed very quickly.

There are basically two kinds of lists that are linked:

 One-Linked Listing: This type of system contains


the guide or address of the next node within the
current node. This means that a node is the last
one to have the address as well as a guide is a
NULL. Example: A > B > C > D > E > NULL.
 Double-Linked Listing: The title suggests that
every node has two references that are related to
it. One reference is directed to the previous node,
and the second reference is directed to the
following node. Traversal is possible both ways
since an example guide is available from the
previous nodes. In addition, the explicit access
requirement isn't needed to delete. Example: NULL
B C D E-> NULL.
 A linked list that has a circular form: elements
in circular linked lists are linked in such a manner
that the group is created. Since the linked list is
circular, there is no limit, and therefore there is no
null. This type of linked checklist has the ability to
be used either doubly or singly. There is no specific
starting point, and any node in the data may be
the starting point. The guide for the last node
points to the first node. Example: A > B > C > D->
E.
3. Stack
The stack is a different type of structure in that
components within the data system adhere to the
principles in LIFO- Last in, First out (or) FILO- First In,
Last Out. Two kinds of operations can be attributed to
the stack, i.e., the pushing and pop operation. Push is
necessary for components that need to be added to
the collection, and pop is employed when the
component previously added needs to be removed
from the collection. The extraction can be removed to
add the final component.

Some examples of stacks include the elimination of


the recursion. In situations where words have to be
reversed or when using editors, if the last word
entered will be removed, stacks are used to begin with
(using the undo function).

4. Queue
The queue is the type of system that stores data in
which components are stored in accordance with an
order of First In, First Out (FIFO). The exact sequence
is followed to carry out the required actions by the
components. The main difference between the queue
and stacks lies in eliminating an element. It is in the
area where the object that was added the most
recently is removed first in the stack. At the same
time, the case with a queue element that was initially
added is removed first.

Both the end and the conclusion of the system are


used for the removal of data and the addition of data.
The two main operations that govern the structure of
the queue are dequeue and enqueue. Enqueue refers
to the procedure where the addition of a component is
allowed to be used in creating data. And dequeue
refers to the method where the removal of
components is allowed. This is the primary aspect of
the queue in this case.

Examples of queues: Like the queues made when


waiting for the bus or anywhere else, the data
structure is similar to the pattern. It is possible to
imagine someone who is waiting for the bus and then
sitting in the first spot as the person who made it to
the queue first. The person who arrived first is likely to
be the first person to get on an actual bus, i.e., get out
of the line. Queues are created when a number of
customers share the same enthusiasm and need to be
served based on the foundation which is first created
for the server.

What Is a Nonlinear Data Structure?

Data structures in which the data elements do not


have to be arranged in a linear or sequential fashion
are referred to as nonlinear data structures. In a
nonlinear structure, only one level of data is not used.
So, it is impossible to traverse the entire structure in
one run. Nonlinear data structures can be
straightforward to design and implement compared to
linear data structures. They make use of computer
memory effectively when compared to a linear
structure. Examples of this are graphs and trees.

1. Trees
A tree can be described as a nonlinear information
system comprised of a variety of nodes. The nodes of
the tree data structure are organized in order of
hierarchy.

It is composed of a root node that corresponds to the


different kids' nodes that are present at the next level.
The tree is built from a level foundation, and root
nodes are minimum kid nodes based on the tree's
growing order. In the tree of binary, the position of the
root has two nodes, which means it has the capacity to
be able to have up to two kids per node and not more
than that.

For Non-Linear Data Structure, the nonlinear system of


data cannot be used directly, so it is implemented
using the linear data structure, such as linked lists and
arrays. The tree itself is a large info structure, and it is
broken down into various kinds like Binary trees,
Binary search trees, Heap, AVL trees max Heap, min-
heap, and many more.

The types of trees mentioned above are different


based on the properties they possess. The term "tree"
refers to an acyclic, nonlinear connected graph. It's a
nonlinear system of data like a tree. A node may be
linked to one or more nodes. It's a collection of nodes
linked by direct (or possibly indirectly) edges. It's
comprised of a significant node called the 'root node.'

2. Graphs
A graph can be described as a nonlinear information
system with a restricted number of vertices and
edges, and these edges are used to join the vertex
pairs. The graph is classified by certain characteristics.
When we talk about a large graph, it is composed of a
set of vertex together with every vertex that is
attached to the various vertex sets, gaining an
advantage over the two. The vertices hold the data
elements, whereas they are the tip of the link between
the vertex sets.

The graph concept is essential in many fields. The


network is represented with the help of the graph
principle as well as its ideas within computer
networks. In Maps, we consider each spot as a vertex,
and the road between two locations is considered an
edge. The main goal of graph representation is to
determine the distance between two vertex points
through an advantage mass that is minimal. You can
explore the complexity on a deeper level by opting
for Computer Programming courses for
beginners through KnowledgeHut.

What Is the Difference Between Linear and Non-Linear


Data Structures?

Linear refers to data components that have been


sequentially attached. Each component can be
traversed in a single run. Nonlinear data structures are
data components that have been hierarchically
attached. Linear and non-linear data structures or all
data components can be found at one level in a linear
data structure.

Let's talk about the differences between Linear or


Nonlinear data structures based on data
arrangements, data elements being transferred,
implementation, levels, and time complexity.
Linear Data Nonlinear Data
Basis of
Structure Structure

Linear data
structures are
data elements
that are Data elements
organized in a nonlinear
Data
linearly. Each data system
Arrangements:
element is are attached
attached to hierarchically.
the next and
previous
adjacent.

Multilevels are
A linear data
possible in
Levels: structure only
nonlinear data
has one level.
structures.

It is more
It is much complicated
Implementatio easier than than a linear
n: nonlinear data data structure
structures. but can be
implemented.
Linear Data Nonlinear Data
Basis of
Structure Structure

Nonlinear data
structures can
Data elements be traversed
in linear data over multiple
Transferring
structures can runs, but data
Data Elements:
only be elements
traversed once cannot be
traversed in
one run.

Memory is
Memory is not
used efficiently
Memory used efficiently
in nonlinear
Usage: in a linear data
data
structure.
structures.

Its examples
are queue, Its examples
Examples: linked list, include graphs
array, stack, and trees.
etc.

Usage: The Artificial


application of Intelligence
Linear Data Nonlinear Data
Basis of
Structure Structure

and Image
linear data Processing are
structures is two examples
mainly used in of applications
software for nonlinear
development. data
structures.

Which Data Structure Is Better: Linear or Non-


Linear?
Nonlinear data structures are data components that
exist at multiple levels. Linear detail structures are
much easier to implement. Linear data structures are
much easier to comprehend and apply than nonlinear
data structures. It is possible to traverse linear data
structures in one run.

Therefore, it is impossible to traverse all components


of each run. It is more difficult to implement nonlinear
data structures than linear data structures. You can
explore the complexity on a deeper level by opting
for Computer Programming courses for beginne

Operations on different Data Structure:


There are different types of operations that can be performed
for the manipulation of data in every data structure. Some
operations are explained and illustrated below:
 Traversing: Traversing a Data Structure means to visit
the element stored in it. It visits data in a systematic
manner. This can be done with any type of DS.
Below is the program to illustrate traversal in an array,
stack, queue and linkedlist:
 Array
 Stack
 Queue
 LinkedList

// C++ program to traversal in an array


#include <iostream>
using namespace std;

// Driver Code
int main()
{
// Initialise array
int arr[] = { 1, 2, 3, 4 };

// size of array
int N = sizeof(arr) / sizeof(arr[0]);

// Traverse the element of arr[]


for (int i = 0; i < N; i++) {

// Print the element


cout << arr[i] << ' ';
}

return 0;
}
Output:
1 2 3 4
Below is the program to illustrate traversal in an array:

 C++
 Java
 Python3
 C#
 Javascript

// C++ program to traversal in an array


#include <bits/stdc++.h>
using namespace std;

// Driver Code
int main()
{
// Initialise array
int arr[] = { 1, 2, 3, 4 };

// size of array
int N = sizeof(arr)/sizeof(arr[0]);

// Traverse the element of arr[]


for (int i = 0; i < N; i++) {

// Print the element


cout << arr[i] << " ";
}
return 0;
}

// This code is contributed by


jana_sayantan.
Below is the program to illustrate traversal in a Stack:

 C++
 Java
 Python3
 C#
 Javascript

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

// Function to print the element in stack


void printStack(stack<int> St){

// Traverse the stack


while (!St.empty()) {

// Print top element


cout << St.top() <<" ";

// Pop top element


St.pop();
}
}

int main() {

// Initialise stack
stack<int> St;

// Insert Element in stack


St.push(4);
St.push(3);
St.push(2);
St.push(1);

// Print elements in stack


printStack(St);
return 0;
}

// This code is contributed by lokesh.


 Searching: Searching means to find a particular
element in the given data-structure. It is considered as
successful when the required element is found.
Searching is the operation which we can performed on
data-structures like array, linked-list, tree, graph, etc.
Below is the program to illustrate searching an element
in an array, stack, queue and linkedlist:

 Array
 Stack
 Queue
 LinkedList

// C++ program to searching in an array


#include <iostream>
using namespace std;

// Function that finds element K in the


// array
void findElement(int arr[], int N, int K)
{

// Traverse the element of arr[]


// to find element K
for (int i = 0; i < N; i++) {

// If Element is present then


// print the index and return
if (arr[i] == K) {
cout << "Element found!";
return;
}
}

cout << "Element Not found!";


}

// Driver Code
int main()
{
// Initialise array
int arr[] = { 1, 2, 3, 4 };

// Element to be found
int K = 3;

// size of array
int N = sizeof(arr) / sizeof(arr[0]);

// Function Call
findElement(arr, N, K);
return 0;
}
Output:
Element found!

 Insertion: It is the operation which we apply on all the


data-structures. Insertion means to add an element in
the given data structure. The operation of insertion is
successful when the required element is added to the
required data-structure. It is unsuccessful in some
cases when the size of the data structure is full and
when there is no space in the data-structure to add any
additional element. The insertion has the same name
as an insertion in the data-structure as an array, linked-
list, graph, tree. In stack, this operation is called Push.
In the queue, this operation is called Enqueue.
Below is the program to illustrate insertion in array,
stack, queue and linkedlist :
 Array
 Stack
 Queue
 LinkedList

// C++ program for insertion in array


#include <iostream>
using namespace std;

// Function to print the array element


void printArray(int arr[], int N)
{
// Traverse the element of arr[]
for (int i = 0; i < N; i++) {

// Print the element


cout << arr[i] << ' ';
}
}
// Driver Code
int main()
{
// Initialise array
int arr[4];

// size of array
int N = 4;

// Insert elements in array


for (int i = 1; i < 5; i++) {
arr[i - 1] = i;
}

// Print array element


printArray(arr, N);
return 0;
}
Output:
1 2 3 4

 Deletion: It is the operation which we apply on all the


data-structures. Deletion means to delete an element
in the given data structure. The operation of deletion is
successful when the required element is deleted from
the data structure. The deletion has the same name as
a deletion in the data-structure as an array, linked-list,
graph, tree, etc. In stack, this operation is called Pop.
In Queue this operation is called Dequeue.
Below is the program to illustrate dequeue in Stack,
Queue and Linkedlist:
 Stack
 Queue
 LinkedList
// C++ program for insertion in array
#include <bits/stdc++.h>
using namespace std;

// Function to print the element in stack


void printStack(stack<int> St)
{
// Traverse the stack
while (!St.empty()) {

// Print top element


cout << St.top() << ' ';

// Pop top element


St.pop();
}
}

// Driver Code
int main()
{
// Initialise stack
stack<int> St;

// Insert Element in stack


St.push(4);
St.push(3);
St.push(2);
St.push(1);

// Print elements before pop


// operation on stack
printStack(St);

cout << endl;


// Pop the top element
St.pop();

// Print elements after pop


// operation on stack
printStack(St);
return 0;
}
Output:
1 2 3 4
2 3 4
#OOPS CONCEPTS:
Object-oriented programming – As the name suggests
uses objects in programming. Object-oriented programming
aims to implement real-world entities like inheritance, hiding,
polymorphism, etc in programming. The main aim of OOP is to
bind together the data and the functions that operate on them
so that no other part of the code can access this data except
that function.
Characteristics of an Object Oriented Programming
language
FEATURES OF C++:
C++ is a general-purpose programming language that was
developed as an enhancement of the C language to include
an object-oriented paradigm. It is an imperative
and compiled language. C++ has a number of features,
including:
 Object-Oriented Programming
 Machine Independent
 Simple
 High-Level Language
 Popular
 Case-sensitive
 Compiler Based
 Dynamic Memory Allocation
 Memory Management
 Multi-threading
1. Object-Oriented Programming
C++ is an Object-Oriented Programming Language, unlike C
which is a procedural programming language. This is the most
important feature of C++. It can create/destroy objects while
programming. Also, It can create blueprints with which objects
can be created. We have discussed the Object-Orient
Programming Concepts in C++ in this article.
Concepts of Object-oriented programming Language:
 Class
 Objects
 Encapsulation
 Polymorphism
 Inheritance
 Abstraction
2. Machine Independent
A C++ executable is not platform-independent (compiled
programs on Linux won’t run on Windows), however, they are
machine-independent. Let us understand this feature of C++
with the help of an example. Suppose you have written a piece
of code that can run on Linux/Windows/Mac OSx which makes
the C++ Machine Independent but the executable file of the C+
+ cannot run on different operating systems.
3. Simple
It is a simple language in the sense that programs can be
broken down into logical units and parts, has rich library
support and has a variety of data types. Also, the Auto
Keyword of C++ makes life easier.

Auto Keyword

The idea of the auto keyword was to form the C++ compiler to
deduce the data type while compiling instead of making you
declare the data type every freaking time. Do keep in mind that
you cannot declare something without an initializer. There
must be some way for the compiler to deduce your type.
Example:
 C++
// C++ program to demonstrate
// working of auto keyword

#include <bits/stdc++.h>
using namespace std;

// Driver Code
int main()
{

// Variables
auto an_int = 26;
auto a_bool = false;
auto a_float = 26.24;
auto ptr = &a_float;

// Print typeid
cout << typeid(a_bool).name() << "\
n";
cout << typeid(an_int).name() << "\
n";
return 0;
}

Output:
b
i

4. High-Level Language
C++ is a High-Level Language, unlike C which is a Mid-Level
Programming Language. It makes life easier to work in C++ as
it is a high-level language it is closely associated with the
human-comprehensible English language.
5. Popular
C++ can be the base language for many other programming
languages that supports the feature of object-oriented
programming. Bjarne Stroustrup found Simula 67, the first
object-oriented language ever, lacking simulations, and
decided to develop C++.
6. Case-sensitive
It is clear that C++ is a case-sensitive programming language.
For example, cin is used to take input from the input stream.
But if the “Cin” won’t work. Other languages like HTML and
MySQL are not case-sensitive languages.
7. Compiler Based
C++ is a compiler-based language, unlike Python. That is C++
programs used to be compiled and their executable file is used
to run them. C++ is a relatively faster language than Java and
Python.
8. Dynamic Memory Allocation
When the program executes in C++ then the variables are
allocated the dynamical heap space. Inside the functions, the
variables are allocated in the stack space. Many times, We are
not aware in advance how much memory is needed to store
particular information in a defined variable and the size of
required memory can be determined at run time.
9. Memory Management
 C++ allows us to allocate the memory of a variable or
an array in run time. This is known as Dynamic
Memory Allocation.
 In other programming languages such
as Java and Python, the compiler automatically
manages the memories allocated to variables. But this
is not the case in C++.
 In C++, the memory must be de-allocated dynamically
allocated memory manually after it is of no use.
 The allocation and deallocation of the memory can be
done using the new and delete operators respectively.
10. Multi-threading
 Multithreading is a specialized form of multitasking and
multitasking is a feature that allows your system to
execute two or more programs concurrently. In general,
there are two sorts of multitasking: process-based and
thread-based.
 Process-based multitasking handles the concurrent
execution of programs. Thread-based multitasking
deals with the multiprogramming of pieces of an
equivalent program.
 A multithreaded program contains two or more parts
that will run concurrently. Each part of such a program
is named a thread, and every thread defines a
separate path of execution.

some applications of OOPs:


 Real-Time System design: Real-time system inherits
complexities and makes it difficult to build them. OOP
techniques make it easier to handle those
complexities.
 Hypertext and Hypermedia: Hypertext is similar to
regular text as it can be stored, searched, and edited
easily. Hypermedia on the other hand is a superset of
hypertext. OOP also helps in laying the framework for
hypertext and hypermedia.
 AI Expert System: These are computer application
that is developed to solve complex problems which are
far beyond the human brain. OOP helps to develop
such an AI expert System
 Office automation System: These include formal as
well as informal electronic systems that primarily
concerned with information sharing and communication
to and from people inside and outside the organization.
OOP also help in making office automation principle.
 Neural networking and parallel programming: It
addresses the problem of prediction and approximation
of complex-time varying systems. OOP simplifies the
entire process by simplifying the approximation and
prediction ability of the network.
 Stimulation and modeling system: It is difficult to
model complex systems due to varying specifications
of variables. Stimulating complex systems require
modeling and understanding interaction explicitly. OOP
provides an appropriate approach for simplifying these
complex models.
 Object-oriented database: The databases try to
maintain a direct correspondence between the real
world and database object in order to let the object
retain it identity and integrity.
 Client-server system: Object-oriented client-server
system provides the IT infrastructure creating object-
oriented server internet(OCSI) applications.
 CIM/CAD/CAM systems: OOP can also be used in
manufacturing and designing applications as it allows
people to reduce the efforts involved. For instance, it
can be used while designing blueprints and flowcharts.
So it makes it possible to produce these flowcharts and
blueprint accurately.

Difference between Structured Programming and Object-


Oriented Programming :
Structured Programming Object-Oriented Programming

It is a subset of procedural It relies on concept of objects that


programming. contain data and code.

Programs are divided into Programs are divided into objects


small programs or functions. or entities.

It is all about facilitating


creation of programs with It is all about creating objects that
readable code and reusable usually contain both functions
components. and data.

Its main aim is to improve and Its main aim is to improve and
increase quality, clarity, and increase both quality and
development time of computer productivity of system analysis
program. and design.

It simply focuses on representing


both structure and behavior of
It simply focuses on functions information system into tiny or
and processes that usually small modules that generally
work on data. combines data and process both.

It is a method of organizing,
managing and coding
programs that can give or It is a method in which set of
provide much easier objects can vary dynamically and
modification and can execute just by acting and
understanding. reading to each other.

In this, methods are written


globally and code lines are In this, method works
processed one by one i.e., Run dynamically, make calls as per
sequentially. need of code for certain time.

It generally follows “Top- It generally follows “Bottom-Up


Down Approach”. Approach”.

It provides less flexibility and It provides more flexibility and


abstraction as compared to abstraction as compared to
object-oriented programming. structured programming.

It is more difficult to modify It is less difficult to modify


structured program and reuse object-oriented programs and
code as compared to object- reuse code as compared to
oriented programs. structured programs.

It gives more importance of


code. It gives more importance to data.

# Character Sets.
C++ Character Set
The character set is a combination of English language comprising of
the Alphabets and the White spaces and some symbols from the
mathematics including the Digits and the Special symbols. C++
character set means the characters and the symbols that are
understandable and acceptable by the C++ Program. These are grouped
to create and give the commands, expressions, words, c-statements, and
some of the other tokens for the C++ Language.
It is basically the combination of alphabets or characters, special
symbols, digits, and white spaces that are similar as the learning
English is to initially learns the alphabets, then learn how to combine
these alphabets to create words, which in turn are joined to make
sentences and sentences are joined to create the paragraphs. More about
a C++ program we can say is that it is basically an order of the
characters arranged in a sequence. These characters come from the
character set and play various roles in many ways in the C++ compiler.
In addition to characters, C++ also uses a mixture of characters to
represent some special conditions as well. For example; Character
combinations like ‘\nt, ‘\b’ and ‘\t’ are used for the representation of the
newline, backspace, and the horizontal tab correspondingly.

C++ Tokens :
A token is the smallest element of a program that is
meaningful to the compiler. Tokens can be classified as
follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1.Keywords: Keywords are pre-defined or reserved words in
a programming language. Each keyword is meant to perform a
specific function in a program. Since keywords are referred
names for a compiler, they can’t be used as variable names
because by doing so, we are trying to assign a new meaning
to the keyword which is not allowed. You cannot redefine
keywords. However, you can specify the text to be substituted
for keywords before compilation by using C/C++ preprocessor
directives. C language supports 32 keywords which are given
below:
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
While in C++ there are 31 additional keywords other
than C Keywords they are:
asm bool catch class
const_cast delete dynamic_cast
explicit
export false friend inline
mutable namespace new
operator
private protected public
reinterpret_cast
static_cast template this throw
true try typeid
typename
using virtual wchar_t
2.Identifiers: Identifiers are used as the general terminology
for the naming of variables, functions and arrays. These are
user-defined names consisting of an arbitrarily long sequence
of letters and digits with either a letter or the underscore(_) as
a first character. Identifier names must differ in spelling and
case from any keywords. You cannot use keywords as
identifiers; they are reserved for special use. Once declared,
you can use the identifier in later program statements to refer
to the associated value. A special kind of identifier, called a
statement label, can be used in goto statements.
There are certain rules that should be followed while
naming c identifiers:

 They must begin with a letter or underscore(_).


 They must consist of only letters, digits, or underscore.
No other special character is allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only the first
31 characters are significant.
 main: method name.
 a: variable name.
3.Constants: Constants are also like normal variables. But,
the only difference is, their values can not be modified by the
program once they are defined. Constants refer to fixed
values. They are also called literals.
Constants may belong to any of the data type
Syntax:
const data_type variable_name; (or) const data_type
*variable_name;
Types of Constants:

1. Integer constants – Example: 0, 1, 1218, 12482


2. Real or Floating-point constants – Example: 0.0,
1203.03, 30486.184
3. Octal & Hexadecimal constants – Example: octal:
(013 )8 = (11)10, Hexadecimal: (013)16 = (19)10
4. Character constants -Example: ‘a’, ‘A’, ‘z’
5. String constants -Example: “GeeksforGeeks”
4.Strings: Strings are nothing but an array of characters
ended with a null character (‘\0’). This null character indicates
the end of the string. Strings are always enclosed in double-
quotes. Whereas, a character is enclosed in single quotes in C
and C++.Declarations for String:

char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’,
‘k’, ‘s’, ‘\0’};
 char string[20] = “geeksforgeeks”;
 char string [] = “geeksforgeeks”;
 when we declare char as “string[20]”, 20 bytes of
memory space is allocated for holding the string value.
 When we declare char as “string[]”, memory space will
be allocated as per the requirement during the
execution of the program.
5.Special Symbols: The following special symbols are used
in C having some special meaning and thus, cannot be used
for some other purpose.[] () {}, ; * = #

 Brackets[]: Opening and closing brackets are used as


array element reference. These indicate single and
multidimensional subscripts.
 Parentheses(): These special symbols are used to
indicate function calls and function parameters.
 Braces{}: These opening and ending curly braces
mark the start and end of a block of code containing
more than one executable statement.
 Comma (, ): It is used to separate more than one
statements like for separating parameters in function
calls.
 Colon(:): It is an operator that essentially invokes
something called an initialization list.
 Semicolon(;): It is known as a statement terminator. It
indicates the end of one logical entity. That’s why each
individual statement must be ended with a semicolon.
 Asterisk (*): It is used to create a pointer variable and
for the multiplication of variables.
 Assignment operator(=): It is used to assign values
and for the logical operation validation.
 Pre-processor (#): The preprocessor is a macro
processor that is used automatically by the compiler to
transform your program before actual compilation.
6.Operators: Operators are symbols that trigger an action
when applied to C variables and other objects. The data items
on which operators act upon are called operands.
Depending on the number of operands that an operator can
act upon, operators can be classified as follows:

 Unary Operators: Those operators that require only a


single operand to act upon are known as unary
operators.For Example increment and decrement
operators
 Binary Operators: Those operators that require two
operands to act upon are called binary
operators. Binary operators are classified into :
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operator
 Ternary Operator: The operator that require three
operands to act upon are called ternary operator.
Conditional Operator(?) is also called ternary operator.
Syntax: (Expression1)? expression2: expression3;
This article is contributed by I.HARISH KUMAR. If you like
GeeksforGeeks and would like to contribute, you can also
write an article using write.geeksforgeeks.org or mail your
article to review-team@geeksforgeeks.org. See your article
appearing on the GeeksforGeeks main page and help other
Geeks.
Please write comments if you find anything incorrect, or you
want to share more information about the topic discussed
above.
Data Types in C++ are Mainly Divided into 3 Types:
1. Primitive Data Types: These data types are built-in or predefined
data types and can be used directly by the user to declare variables.
example: int, char, float, bool, etc. Primitive data types available in
C++ are:
 Integer
 Character
 Boolean
 Floating Point
 Double Floating Point
 Valueless or Void
 Wide Character
2. Derived Data Types: Derived data types that are derived from the
primitive or built-in datatypes are referred to as Derived Data Types.
These can be of four types namely:
 Function
 Array
 Pointer
 Reference
3. Abstract or User-Defined Data Types: Abstract or User-Defined
data types are defined by the user itself. Like, defining a class in C++
or a structure. C++ provides the following user-defined datatypes:
 Class
 Structure
 Union
 Enumeration
 Typedef defined Datatype
Primitive Data Types
 Integer: The keyword used for integer data types is int.
Integers typically require 4 bytes of memory space and range
from -2147483648 to 2147483647.
 Character: Character data type is used for storing characters.
The keyword used for the character data type is char.
Characters typically require 1 byte of memory space and
range from -128 to 127 or 0 to 255.
 Boolean: Boolean data type is used for storing Boolean or
logical values. A Boolean variable can store
either true or false. The keyword used for the Boolean data
type is bool.
 Floating Point: Floating Point data type is used for storing
single-precision floating-point values or decimal values. The
keyword used for the floating-point data type is float. Float
variables typically require 4 bytes of memory space.
 Double Floating Point: Double Floating Point data type is
used for storing double-precision floating-point values or
decimal values. The keyword used for the double floating-
point data type is double. Double variables typically require
8 bytes of memory space.
 void: Void means without any value. void data type
represents a valueless entity. A void data type is used for
those function which does not return a value.
 Wide Character: Wide character data type is also a character
data type but this data type has a size greater than the
normal 8-bit data type. Represented by wchar_t. It is
generally 2 or 4 bytes long.
 sizeof() operator: sizeof() operator is used to find the
number of bytes occupied by a variable/data type in
computer memory.
Example:
int m , x[50];
cout<<sizeof(m); //returns 4 which is the number of bytes occupied
by the integer variable “m”.
cout<<sizeof(x); //returns 200 which is the number of bytes occupied
by the integer array variable “x”.
The size of variables might be different from those shown in the
above table, depending on the compiler and the computer you are
using.

 C++
// C++ Program to Demonstrate the correct
size
// of various data types on your
computer.
#include <iostream>
using namespace std;

int main()
{
cout << "Size of char : " <<
sizeof(char) << endl;
cout << "Size of int : " <<
sizeof(int) << endl;

cout << "Size of long : " <<


sizeof(long) << endl;
cout << "Size of float : " <<
sizeof(float) << endl;

cout << "Size of double : " <<


sizeof(double) << endl;

return 0;
}

Output

Format specifiers in C++


The format specifier is used during input and output.
It is a way to tell the compiler what type of data is in a
variable during taking input using scanf() or printing
using printf(). Some examples are %c, %d, %f, etc.

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:
1. iostream: iostream stands for standard input-output
stream. This header file contains definitions of objects
like cin, cout, cerr, etc.
2. iomanip: iomanip stands for input-output manipulators.
The methods declared in these files are used for
manipulating streams. This file contains definitions of
setw, setprecision, etc.
3. fstream: This header file mainly describes the file
stream. This header file is used to handle the data
being read from a file as input or data being written into
the file as output.
4. bits/stdc++: This header file includes every standard
library. In programming contests, using this file is a
good idea, when you want to reduce the time wasted in
doing chores; especially when your rank is time
sensitive. To know more about this header file
refer this article.
In C++ after the header files, we often use ‘using namespace
std;‘. The reason behind it is that all of the standard library
definitions are inside the namespace std. As the library
functions are not defined at global scope, so in order to use
them we use namespace std. So, that we don’t need to write
STD:: at every line (eg. STD::cout etc.). To know more
refer this article.
The two instances cout in C++ and cin in C++ of iostream
class are used very often for printing outputs and taking inputs
respectively. These two are the most basic methods of taking
input and printing output in C++. To use cin and cout in C++
one must include the header file iostream in the program.
This article mainly discusses the objects defined in the header
file iostream like the cin and cout.
 Standard output stream (cout): Usually the standard
output device is the display screen. The C+
+ cout statement is the instance of the ostream class.
It is used to produce output on the standard output
device which is usually the display screen. The data
needed to be displayed on the screen is inserted in the
standard output stream (cout) using the insertion
operator(<<).
 C++
#include <iostream>

using namespace std;

int main()
{
char sample[] = "GeeksforGeeks";

cout << sample << " - A computer


science portal for geeks";

return 0;
}

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

int main()
{
int age;

cout << "Enter your age:";


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

return 0;
}

Input :
18
Output:
Enter your age:
Your age is: 18

Structure of C++ Program


The C++ program is written using a specific template structure.
The structure of the program written in C++ language is as
follows:
Documentation Section:
 This section comes first and is used to document the
logic of the program that the programmer going to
code.
 It can be also used to write for purpose of the program.
 Whatever written in the documentation section is the
comment and is not compiled by the compiler.
 Documentation Section is optional since the program
can execute without them. Below is the snippet of the
same:
 C++
/* This is a C++ program to find the
factorial of a number

The basic requirement for writing


this
program is to have knowledge of loops

To find the factorial of number


iterate over range from number to one
*/

Linking Section:
The linking section contains two parts:
Header Files:
 Generally, a program includes various programming
elements like built-in functions, classes,
keywords, constants, operators, etc. that are already
defined in the standard C++ library.
 In order to use such pre-defined elements in a
program, an appropriate header must be included in
the program.
 Standard headers are specified in a program through
the preprocessor directive #include. In Figure, the
iostream header is used. When the compiler processes
the instruction #include<iostream>, it includes the
contents of the stream in the program. This enables the
programmer to use standard input, output, and error
facilities that are provided only through the standard
streams defined in <iostream>. These standard
streams process data as a stream of characters, that
is, data is read and displayed in a continuous flow. The
standard streams defined in <iostream> are listed
here.
#include<iostream>
Namespaces:
 A namespace permits grouping of various entities like
classes, objects, functions, and various C++ tokens,
etc. under a single name.
 Any user can create separate namespaces of its own
and can use them in any other program.
 In the below snippets, namespace std contains
declarations for cout, cin, endl, etc. statements.
using namespace std;
 Namespaces can be accessed in multiple ways:
 using namespace std;
 using std :: cout;
Definition Section:
 It is used to declare some constants and assign them
some value.
 In this section, anyone can define your
own datatype using primitive data types.
 In #define is a compiler directive which tells the
compiler whenever the message is found to replace it
with “Factorial\n”.
 typedef int INTEGER; this statement tells the compiler
that whenever you will encounter INTEGER replace it
by int and as you have declared INTEGER as datatype
you cannot use it as an identifier.
Global Declaration Section:
 Here, the variables and the class definitions which are
going to be used in the program are declared to make
them global.
 The scope of the variable declared in this section lasts
until the entire program terminates.
 These variables are accessible within the user-defined
functions also.
Function Declaration Section :
 It contains all the functions which our main functions
need.
 Usually, this section contains the User-defined
functions.
 This part of the program can be written after the main
function but for this, write the function prototype in this
section for the function which for you are going to write
code after the main function.
 C++
// Function to implement the
// factorial of number num
INTEGER factorial(INTEGER num)
{
// Iterate over the loop from
// num to one
for (INTEGER i = 1; i <= num; i++) {
fact *= i;
}

// Return the factorial calculated


return fact;
}

Main Function:
 The main function tells the compiler where to start the
execution of the program. The execution of the
program starts with the main function.
 All the statements that are to be executed are written in
the main function.
 The compiler executes all the instructions which are
written in the curly braces {} which encloses the body
of the main function.
 Once all instructions from the main function are
executed, control comes out of the main function and
the program terminates and no further execution occur.
Below is the program to illustrate this:

 C++
// Documentation Section
/* This is a C++ program to find the
factorial of a number
The basic requirement for writing
this
program is to have knowledge of loops
To find the factorial of a number
iterate over the range from number to
1
*/

// Linking Section
#include <iostream>
using namespace std;

// Definition Section
#define msg "FACTORIAL\n"
typedef int INTEGER;

// Global Declaration Section


INTEGER num = 0, fact = 1, storeFactorial
= 0;

// Function Section
INTEGER factorial(INTEGER num)
{
// Iterate over the loop from
// num to one
for (INTEGER i = 1; i <= num; i++) {
fact *= i;
}

// Return the factorial


return fact;
}

// Main Function
INTEGER main()
{
// Given number Num
INTEGER Num = 5;

// Function Call
storeFactorial = factorial(Num);
cout << msg;

// Print the factorial


cout << Num << "! = "
<< storeFactorial << endl;

return 0;
}

Output
FACTORIAL
5! = 120
In C++, Control Statements are usually jumped from
one part of the C++ code to another depending on
whether a particular condition is satisfied or not. There
are three types of C++ Control Statements are given as
follows:
1. Sequence Statement
2. Selection Statement
3. Loop Statement

Types of Control Statements in C++:

if-else statement:
if-else statement is used to execute a statement block.
It has the following syntax :
 if(expression is true
 {
 action 1;
 }
 else
 {
 action 2;
 }

switch statement:
It is a multiple branching statement where based on a
condition, the control is transferred to one of the many
possible points. It has the following syntax:
 switch(expression)
 {
 case1:
 {
 action 1;
 }
 case 2:
 {
 action 2;
 }
 case 3:
 {
 action 3;
 }
 default:
 {
 default statement;
 }
 }

for statement:
for is an entry controlled loop. It is used when an action
is to be repeated for a predetermined time. It has the
following syntax:
 for(initial value; test condition; increment or
decrement)
 {
 action 1;
 }

while statement:
It is also a loop control structure but it’s an entry-
controlled loop.
It has the following syntax:
 while(condition is true)
 {
 action 1;
 }
 action 2;

do-while statement:
do-while is an exit controlled loop based on a
condition, the control is transferred back to a particular
point in the program. It has the following syntax:
 do
 {
 action;
 }
 while(condition is true);
 action 2;

LOOPS program
#include <iostream>
using namespace std;
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}
C++ Classes and Objects
Class:
A class in C++ is the building block that leads to Object-
Oriented programming. It is a user-defined data type, which
holds its own data members and member functions, which can
be accessed and used by creating an instance of that class. A
C++ class is like a blueprint for an object. For Example:
Consider the Class of Cars. There may be many cars with
different names and brand but all of them will share some
common properties like all of them will have 4 wheels, Speed
Limit, Mileage range etc. So here, Car is the class and wheels,
speed limits, mileage are their properties.
 A Class is a user defined data-type which has data
members and member functions.
 Data members are the data variables and member
functions are the functions used to manipulate these
variables and together these data members and
member functions defines the properties and behavior
of the objects in a Class.
 In the above example of class Car, the data member
will be speed limit, mileage etc and member functions
can be apply brakes, increase speed etc

OBJECT:
An Object is an instance of a Class. When a class is defined,
no memory is allocated but when it is instantiated (i.e. an
object is created) memory is allocated.
Defining Class and Declaring Objects
A class is defined in C++ using keyword class followed by the
name of class. The body of class is defined inside the curly
brackets and terminated by a semicolon at the end.
Declaring Objects: When a class is defined, only the
specification for the object is defined; no memory or storage is
allocated. To use the data and access functions defined in the
class, you need to create objects. Syntax: ClassName
ObjectName;

Difference between object and class


There are many differences between object and class. A
list of differences between object and class are given
below:
No Object Class
.

1) Object is an instance of a class. Class is a bluepri


template from
objects are create
2) Object is a real world entity such as Class is a grou
pen, laptop, mobile, bed, keyboard, similar objects.
mouse, chair etc.
3) Object is a physical entity. Class
a logical entity.
4) Object is created through new Class is dec
keyword mainly e.g. using class
Student s1=new Student(); keyword e.g.
class Student{}
5) Object is created many times as per Class is declared o
requirement.
6) Object allocates memory when it is Class doesn't
created. allocated me
when it is create
7) There are many ways to create There is only one
object in java such as new keyword, to define class in
newInstance() method, clone() method, using class keywo
factory method and deserialization.

Access Specifiers

By now, you are quite familiar with the public keyword


that appears in all of our class examples:

Example
class MyClass { // The class
public: // Access specifier
// class members goes here
};

Try it Yourself »

The public keyword is an access specifier. Access


specifiers define how the members (attributes and
methods) of a class can be accessed. In the example
above, the members are public - which means that
they can be accessed and modified from outside the
code.
However, what if we want members to be private and
hidden from the outside world?

In C++, there are three access specifiers:

 public - members are accessible from outside the


class
 private - members cannot be accessed (or
viewed) from outside the class
 protected - members cannot be accessed from
outside the class, however, they can be accessed
in inherited classes. You will learn more
about Inheritance later.

In the following example, we demonstrate the


differences between public and private members:

Example
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};

int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}

If you try to access a private member, an error occurs:


error: y is private
Try it Yourself »
Class Methods

Methods are functions that belongs to the class.

There are two ways to define functions that belongs to


a class:

 Inside class definition


 Outside class definition

In the following example, we define a function inside


the class, and we name it "myMethod".

Note: You access methods just like you access


attributes; by creating an object of the class and using
the dot syntax (.):

Inside Example
class MyClass { // The class
public: // Access specifier
void myMethod() { // Method/function
defined inside the class
cout << "Hello World!";
}
};

int main() {
MyClass myObj; // Create an object of
MyClass
myObj.myMethod(); // Call the method
return 0;
}

Try it Yourself »

To define a function outside the class definition, you


have to declare it inside the class and then define it
outside of the class. This is done by specifiying the
name of the class, followed the scope
resolution :: operator, followed by the name of the
function:

Outside Example
class MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function
declaration
};

// Method/function definition outside the


class
void MyClass::myMethod() {
cout << "Hello World!";
}

int main() {
MyClass myObj; // Create an object of
MyClass
myObj.myMethod(); // Call the method
return 0;
}

Try it Yourself »
The variables which are declared in any class by using
any fundamental data types (like int, char, float etc) or
derived data type (like class, structure, pointer etc.) are
known as Data Members. And the functions which are
declared either in private section of public section are
known as Member functions.
There are two types of data members/member
functions in C++:
1. Private members
2. Public members
1) Private members
The members which are declared in private section of
the class (using private access modifier) are known as
private members. Private members can also be
accessible within the same class in which they are
declared.
2) Public members
The members which are declared in public section of
the class (using public access modifier) are known as
public members. Public members can access within the
class and outside of the class by using the object name
of the class in which they are declared.
Consider the example:
class Test
{
private:
int a;
float b;
char *name;

void getA() { a=10; }


...;
public:
int count;
void getB() { b=20; }

...;
};
Here, a, b, and name are the private data members
and count is a public data member. While, getA() is a
private member function and getB() is public member
functions.
ADVERTISEMENT
C++ program that will demonstrate, how to
declare, define and access data members an
member functions in a class?
#include <iostream>
#include <string.h>
using namespace std;

#define MAX_CHAR 30

//class definition
class person
{
//private data members
private:
char name [MAX_CHAR];
int age;
//public member functions
public:
//function to get name and age
void get(char n[], int a)
{
strcpy(name , n);
age = a;
}
//function to print name and age
void put()
{
cout<< "Name: " << name <<endl;
cout<< "Age: " <<age <<endl;
}
};

//main function
int main()
{
//creating an object of person class
person PER;

//calling member functions


PER.get("Manju Tomar", 23);
PER.put();

return 0;
}
Output
Name: Manju Tomar
Age: 23

Constructor in C++ is a special method that is invoked


automatically at the time of object creation. It is used to
initialize the data members of new objects generally. The
constructor in C++ has the same name as the class or
structure. Constructor is invoked at the time of object creation.
It constructs the values i.e. provides data for the object which
is why it is known as constructors.
 Constructors are the special members of the class which

initialize the object of class.


 A constructor is automatically invoked at the creation of

the object.
 It is generally used to initialize variables.

 It has the same name as of class.

It does not have any return type(i.e. void, int, etc).

FEATURE:
Characteristics of Constructors
o The name of the constructor must be same as that of the
class

o No return type can be specified for constructor

o A constructor can have parameter list

o The constructor function can be overloaded

o They cannot be inherited but a derived class can call the


base class constructor

o The compiler generates a constructor, in the absence of a


user defined constructor.

Types of Constructor in C++:


 Default constructor
 Parameterized constructor
 Copy constructor

Default Constructor
A constructor that doesn’t have parameters. It is invoked
automatically and can carry default values. If we do not define
constructor it will still define an empty constructor implicitly.

class A
{
public:
int a,b;
A() //Default cosntructor
{
a=10; //random values
b=20;
}
};
int main()
{
A obj; //constructor invoked
cout<<"a= "<<obj.a<<endl;
cout<<"b= "<<obj.b<<endl;
return 0;
}
Output:

a= 10
b= 20

Parameterized Constructor in C++


When we can pass values to constructor it is called
parameterized constructor. Passing values to the constructors
are same as with functions. It is used to initialize variables in a
class.

Class A
{
private:
int x,y;
public:
A(int a,int b) //Parameterized Constructor
{
x=a;
y=b;
}
};
int main()
{
A obj(10,20); //constructor called
cout<<"x= "<<obj.x<<endl; //accessing value by
constructor
cout<<"y= "<<obj.y<<endl;
}
Output:

x= 10
y= 20

Copy Constructor in C++


A copy constructor is used to copy the variable of one object
into another object. It can be written as :

class_name(const class_name &old_obj);

class A{
private:
int a,b;
public:
A(int x,int y)
{
a=x;
b=y;
}
A(const A &obj1) //copy constructor
{
a=obj1.x;
b=obj1.y;
}
};
int main()
{
A obj1(10,20); //Normal constructor
cout<<obj1.a<<" "<<obj1.b<<endl;
A obj2(obj1); //copy constructor call
cout<<obj2.a<<" "<<obj2.b<<endl;
return 0;
}
Output:

What is a destructor?
Destructor is an instance member function which is invoked
automatically whenever an object is going to be destroyed.
Meaning, a destructor is the last function that is going to be
called before an object is destroyed.
 Destructor is also a special member function like
constructor. Destructor destroys the class objects
created by constructor.
 Destructor has the same name as their class name
preceded by a tilde (~) symbol.
 It is not possible to define more than one destructor.
 The destructor is only one way to destroy the object
create by constructor. Hence destructor can-not be
overloaded.
 Destructor neither requires any argument nor returns
any value.
 It is automatically called when object goes out of
scope.
 Destructor release memory space occupied by the
objects created by constructor.
 In destructor, objects are destroyed in the reverse of
an object creation.

The thing is to be noted here, if the object is created by using


new or the constructor uses new to allocate memory which
resides in the heap memory or the free store, the destructor
should use delete to free the memory.
Syntax:
Syntax for defining the destructor within the
class
~ <class-name>()
{

}
Syntax for defining the destructor outside the
class
<class-name>: : ~ <class-name>()
{

 C++

// Example:

#include<iostream>
using namespace std;

class Test
{
public:
Test()
{
cout<<"\n Constructor
executed";
}

~Test()
{
cout<<"\n Destructor
executed";
}
};
main()
{
Test t;

return 0;
}
Output
Constructor executed
Destructor executed

 C++

// Example:

Difference between Constructor and Destructor


in C++ :
S.
No. Constructor Destructor

Whereas destructor is
Constructor helps to initialize used to destroy the
1. the object of a class. instances.

It is declared Whereas it is declared


as className( arguments if any as ~ className( no
2. ){Constructor’s Body }. arguments ){ }.

Constructor can either accept While it can’t have any


3. arguments or not. arguments.

A constructor is called when an It is called while object of


instance or object of a class is the class is freed or
4. created. deleted.

5. Constructor is used to allocate While it is used to


the memory to an instance or deallocate the memory of
S.
No. Constructor Destructor

object. an object of a class.

While it can’t be
6. Constructor can be overloaded. overloaded.

Here, its name is also


same as the class name
The constructor’s name is same preceded by the tiled (~)
7. as the class name. operator.

In a class, there can be multiple While in a class, there is


8. constructors. always a single destructor.

There is a concept of copy


constructor which is used to
initialize an object from another While here, there is no
9. object. copy destructor concept.

They are often called in


They are often called in reverse order of
10. successive order. constructor.

You might also like