C++ Programming
C++ Programming
What is C++?
C++ is a general purpose, case-sensitive, free-form programming language that supports object-
oriented, procedural and generic programming.
C++ is an object-oriented programming language. It is an extension to C programming.
C++ is a middle-level language, as it encapsulates both high and low level language features.
1) Inheritance
2) Polymorphism
3) Encapsulation
4) Abstraction
1) The core library includes the data types, variables and literals, etc.
2) The standard library includes the set of functions manipulating strings, files, etc.
3) The Standard Template Library (STL) includes the set of methods manipulating a data
structure.
Usage of C++
By the help of C++ programming language, we can develop different types of secured and
robust applications:
1) Window application
2) Client-Server application
3) Device drivers
4) Embedded firmware etc
C++ Features
C++ is a widely used programming language.
It provides a lot of features that are given below.
1) Simple
2) Abstract Data types
3) Machine Independent or Portable
4) Mid-level programming language
5) Structured programming language
6) Rich Library
7) Memory Management
8) Quicker Compilation
9) Pointers
10) Recursion
11) Extensible
12) Object-Oriented
13) Compiler based
14) Reusability
15) National Standards
16) Errors are easily detected
17) Power and Flexibility
18) Strongly typed language
19) Redefine Existing Operators
20) Modelling Real-World Problems
21) Clarity
C++ Program
#include<iostream.h> includes the standard input output library functions. It
provides cin and cout methods for reading from input and writing to output respectively.
void main() The main() function is the entry point of every program in C++ language. The void
keyword specifies that it returns no value.
cout << "Hello World" <<endl;is used to print the data on the console.
<iostream> It is used to define the cout, cin and cerr objects, which correspond to standard outputstream,
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.
C++ Variable
A variable is a name of memory location. It is used to store data. Its value can be changed and
it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
The example of declaring variable is given below:
1) int x;
2) float y;
3) char z;
Here, x, y, z are variables and int, float, char are data types.
1) int a;
2) int _ab;
3) int a30;
1) int 4;
2) int x y;
3) int double;
Operators in C++
An operator is simply a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise etc.
There are following types of operators to perform different types of operations in C language.
1) Arithmetic Operators
2) Relational Operators
3) Logical Operators
4) Assignment Operator
5) Unary operator
6) Ternary or Conditional Operator
Arithmetic Operators
These operators used to perform common mathematical operations
Relational Operators
These operators are used to compare two values.
Assignment Operator
These operators are used to assign values to variables.
Logical Operators
These operators are used to determine the logic between variables or values.
1) if statement
2) if-else statement
3) nested if statement
4) if-else-if ladder
C++ IF Statement
The C++ if statement tests the condition. It is executed if condition is true.
1) if(condition){
2) //code to be executed
3) }
C++ IF-else Statement
The C++ if-else statement also tests the condition. It executes if block if condition is true
otherwise else block is executed.
1) if(condition){
2) //code if condition is true
3) }else{
4) //code if condition is false
5) }
1) if(condition1){
2) //code to be executed if condition1 is true
3) }else if(condition2){
4) //code to be executed if condition2 is true
5) }
6) else if(condition3){
7) //code to be executed if condition3 is true
8) }
9) ...
10) else{
11) //code to be executed if all the conditions are false
12) }
C++ nested if
if inside if.
Syntax:
1. If(condition)
2. {
3. If(condition)
4. {
5. //code to be executed
6. }
7. else
8. {
9. //code to be executed
10.}
11.}
C++ switch
The C++ switch statement executes one statement from multiple conditions. It is like if-else-if
ladder statement in C++.
A switch statement is a conditional statement used in C programming to check the value of a
variable and compare it with all the cases.
If the value is matched with any case, then its corresponding statements will be executed. Each
case has some name or number known as the identifier.
The value entered by the user will be compared with all the cases until the case is found. If the
value entered by the user is not matched with any case, then the default statement will be
executed.
Syntax:
1) switch(expression){
2) case value1:
3) //code to be executed;
4) break;
5) case value2:
6) //code to be executed;
7) break;
8) ......
9)
10) default:
11) //code to be executed if all cases are not matched;
12) break;
13) }
C++ Ternary Operator
Ternary Operator works as if-else statement.
We use this operator to run code when the condition is true and another code when the
condition is false.
Syntax:
(condition) ? (expression 1//true part) : (expression 2//false part)
Program:
Program to check whether a character is a vowel or consonant.
C++ Loops
Example:
1) while(condition){
2) //code to be executed
3) }
1) do{
2) //code to be executed
3) }while(condition);
C++ break Statement
The C++ break is used to break loop or switch statement.
It breaks the current flow of the program at the given condition. In case of inner loop, it breaks
only inner loop.
Syntax:
1) jump-statement;
2) break;
Program:
C++ continue Statement
The C++ continue statement is used to continue loop.
It continues the current flow of the program and skips the remaining code at specified
condition. In case of inner loop, it continues only inner loop.
Syntax:
1) jump-statement;
2) continue;
C++ Array
An array is defined as the collection of similar type of data items stored at contiguous memory
locations. Arrays are the derived data type in C++ programming language which can store the
primitive type of data such as int, char, double, float, etc.
It also has the capability to store the collection of derived data types, such as pointers,
structure, etc.
The array is the simplest data structure where each data element can be randomly accessed by
using its index number.
C++ array is beneficial if you have to store similar elements.
For example, if we want to store the marks of a student in 6 subjects, then we don't need to
define different variables for the marks in the different subject.
Instead of that, we can define an array which can store the marks in each subject at the
contiguous memory locations.
By using the array, we can access the elements easily. Only a few lines of code are required to
access the elements of the array.
Advantages of C Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantages of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the
limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.
Properties of Array
The array contains the following properties.
Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
Elements of the array are stored at contiguous memory locations where the first element is
stored at the smallest memory location.
Elements of the array can be randomly accessed since we can calculate the address of each
element of the array with the given base address and the size of the data element.
Declaration of C Array
To declare an array, define the variable type, specify the name of the array followed by square
brackets and specify the number of elements it should store.
data_type array_name[array_size];
Now, let us see the example to declare the array.
1) int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array size.
1) int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define the size. So it may also be written as the
following code.
1) int marks[]={20,30,40,50,60};
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
2) int twodimen[4][3];
Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and initialization
are being done simultaneously.
However, this will not work with 2D arrays. We will have to define at least the second dimension
of the array.
The two-dimensional array can be declared and defined in the following way.
1) int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Addition of matrix:
C++ Functions
In C++, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}.
A function can be called multiple times to provide reusability and modularity to the C program.
In other words, we can say that the collection of functions creates a program.
The function is also known as procedure or subroutine in other programming languages.
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
Functions are used to perform certain actions, and they are important for reusing code: Define
the code once, and use it many times.
Advantages of functions in C
There are the following advantages of C functions.
1) By using functions, we can avoid rewriting same logic/code again and again in a program.
2) We can call C functions any number of times in a program and from any place in a program.
3) We can track a large C program easily when it is divided into multiple functions.
4) Reusability is the main achievement of C functions.
5) However, Function calling is always a overhead in a C program.
Types of Functions
There are two types of functions in C programming:
1. Library Functions: are the functions which are declared in the C++ header files such as ceil(x), cos(x),
exp(x), etc.
2. User-defined functions: are the functions which are created by the C++ programmer, so that
he/she can use it many times. It reduces complexity of a big program and optimizes the code.
Declaration of a function
The syntax of creating function in C++ language is given below,
Create a Function
C++ provides some pre-defined functions, such as main(), which is used to execute code. But
you can also create your own functions to perform certain actions.
To create (often referred to as declare) a function, specify the name of the function, followed
by parentheses ():
Syntax
1) void myFunction()
2) {
//code
}
Example Explained
Call a Function
Declared functions are not executed immediately. They are "saved for later use", and will be
executed later, when they are called.
To call a function, write the function's name followed by two parentheses () and a semicolon ;
In the following example, myFunction() is used to print a text (the action), when it is called:
Call by value and call by reference in C++
There are two ways to pass value or data to function in C language: call by value and call by
reference.
Original value is not modified in call by value but it is modified in call by reference.
Recursion in C++
Recursion is the process which comes into existence when a function calls a copy of itself to
work on a smaller problem. Any function which calls itself is called recursive function, and such
function calls are called recursive calls.
Recursion involves several numbers of recursive calls. However, it is important to impose a
termination condition of recursion.
Recursion code is shorter than iterative code however it is difficult to understand.
Recursion is the technique of making a function call itself.
This technique provides a way to break complicated problems down into simple problems
which are easier to solve.
Recursion may be a bit difficult to understand. The best way to figure out how it works is to
experiment with it.
Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be
defined in terms of similar subtasks.
For Example, recursion may be applied to sorting, searching, and traversal problems.
Example: Adding two numbers together is easy to do, but adding a range of numbers is more
complicated. In the following example, recursion is used to add a range of numbers together
by breaking it down into the simple task of adding two numbers:
Default arguments in C++
You can also use a default parameter value, by using the equals sign (=).
In a function, arguments are defined as the values passed when a function is called. Values
passed are the source, and the receiving function is the destination.
Definition
A default argument is a value in the function declaration automatically assigned by the compiler
if the calling function does not pass any value to that argument.
1) The values passed in the default arguments are not constant. These values can be overwritten
if the value is passed to the function. If not, the previously declared value retains.
2) During the calling of function, the values are copied from left to right.
3) All the values that will be given default value will be on the right.
C++ Strings
Strings are used for storing text.
However, you could also add a space with quotes (" " or ' '). And you can also concatenate
strings with the append() function.
Note: C++ uses the + operator for both addition and concatenation.
Numbers are added. Strings are concatenated.
String Length
To get the length of a string, use the length() function.
Access Strings
You can access the characters in a string by referring to its index number inside square
brackets [].
What is OOP?
OOP stands for Object-Oriented Programming.
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You
should extract out the codes that are common for the application, and place them at a single
place and reuse them instead of repeating it.
C++ supports the object-oriented programming, the four major pillar of object-oriented
programming (OOPs) used in C++ are:
1) Inheritance
2) Polymorphism
3) Encapsulation
4) Abstraction
C++ Classes/Objects
C++ is an object-oriented programming language.
Everything in C++ is associated with classes and objects, along with its attributes and methods.
For example: in real life, a car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.
Attributes and methods are basically variables and functions that belongs to the class. These
are often referred to as "class members".
A class is a user-defined data type that we can use in our program, and it works as an object
constructor, or a "blueprint" for creating objects.
Classes and objects are the two main aspects of object-oriented programming.
Create an Class
To create a class, use the class keyword.
Example explained
1) The class keyword is used to create a class called MyClass.
2) The public keyword is an access specifier, which specifies that members (attributes and
methods) of the class are accessible from outside the class. You will learn more about access
specifiers later.
3) Inside the class, there is an integer variable myNum and a string variable myString. When
variables are declared within a class, they are called attributes.
4) At last, end the class definition with a semicolon ;.
Create an Object
In C++, an object is created from a class. We have already created the class named MyClass, so
now we can use this to create objects.
To create an object of MyClass, specify the class name, followed by the object name.
To access the class attributes (myNum and myString), use the dot syntax (.) on the object:
Example
Create an object called "myObj" and access the attributes:
Here, student is class name, getmarks() and putmarks() are the public functions but int marks;
is private because by default anything in c++ is private, therefore int marks; is private data
member.
Then
s is the object of the class student and accessed all methods using object name.
Another example of class and object:
Multiple Objects
You can create multiple objects of one class.
Class Methods
Methods are functions that belongs to the class.
Note: You access methods just like you access attributes; by creating an object of the class and
using the dot syntax (.)
Inside class example:
1) Default constructor
2) Parameterized constructor
3) Copy constructor
In C++, a constructor has the same name as that of the class and it does not have a return type.
For example,
Here, the function Wall() is a constructor of the class Wall. Notice that the constructor
1) has the same name as the class,
3) is public
C++ Default Constructor
A constructor with no parameters is known as a default constructor. In the example above,
Wall() is a default constructor.
A constructor which has no argument is known as default constructor.
It is invoked at the time of creating object.
copy constructor is a special constructor for creating a new object as a copy of an existing
object.
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.
Constructor overloading
As there is a concept of function overloading, similarly constructor overloading is applied. When
we overload a constructor more than a purpose it is called constructor overloading.
The declaration is the same as the class name but as they are constructors, there is no return
type.
The criteria to overload a constructor is to differ the number of arguments or the type of
arguments.
C++ this Pointer
In C++ programming, this is a keyword that refers to the current instance of the class. There can
be 3 main usage of this keyword in C++.
C++ Inheritance
Inheritance is one of the key features of Object-oriented programming in C++. It allows us to
create a new class (derived class) from an existing class (base class).
The derived class inherits the features from the base class and can have additional features of
its own.
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.
Here, the Dog class is derived from the Animal class. Since Dog is derived from Animal, members
of Animal are accessible to Dog.
We can also use the keywords private and protected instead of public. We will learn about the
differences between using private, public and protected later in this tutorial.
The various ways we can derive classes are known as access modes. These access modes have
the following effect:
1) public: If a derived class is declared in public mode, then the members of the base class
are inherited by the derived class just as they are.
2) private: In this case, all the members of the base class become private members in the
derived class.
3) protected: The public members of the base class become protected members in the
derived class.
The private members of the base class are always private in the derived class.
Types Of Inheritance
C++ supports five types of inheritance:
1) Single inheritance
2) Multiple inheritance
3) Hierarchical inheritance
4) Multilevel inheritance
5) Hybrid inheritance
In multilevel inheritance, a child class inherits all the properties from all of its parent classes.
The base class is the parent class of all sub-classes in multilevel inheritance.
Inheritance goes from parent to child. Parent classes cannot access the properties of the child
class.
C++ Multiple Inheritance
Multiple Inheritance is the concept of inheritance in C++ by which we can inherit data members
and member functions from multiple(more than one) base/parent class(es) so that the derived
class can have properties from more than one parent class.
Multiple inheritance is the process of deriving a new class that inherits the attributes from two
or more classes.
Ambiquity problem 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.
Ambiguity Resolution in inheritance
This problem can be solved using the scope resolution (::) operator. By using the scope
resolution operator, we can specify the base class from which the function is called.
We need to use the scope resolution (::) operator in the main() body of the code after we
declare the object and while calling the member function by the object.
The above issue can be resolved by using the class resolution operator with the function. In the
above example, the derived class code can be rewritten as:
1) Inheritance in C++ promotes Code reusability. When a derived class inherits the base
class, then the derived class can access all the functionality, and the base class's code can
be reused in the derived class.
2) It improves code readability as you don’t have to rewrite the same code repeatedly;
hence, the code looks cleaner and readable.
3) It saves time and effort as the code is already written and is inherited; therefore, it saves
time to write code again.
4) Inheritance supports extensibility as new classes can be easily added to existing classes.
C++ Pointers
The pointer in C++ language is a variable, it is also known as locator or indicator that points to
an address of a value.
When we declare a variable in C++, a specific location in memory is assigned to it to store a
value in this variable. This location is called the memory address of the variable.
Pointers in C++ are special variables that store the memory address of other variables.
Pointers add more features and flexibility to the C++ programming language.
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc.
and used with arrays, structures and functions.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
There are many usage of pointers in C++ language.
In c language, we can dynamically allocate memory using malloc() and calloc() functions where
pointer is used.
Declaring a pointer
The pointer in C++ language can be declared using ∗ (asterisk symbol).
classname*pointertoobject;
For storing the address of an object into a pointer in c++, we use the following syntax:
pointertoobject= &objectname;
The above syntax can be used to store the address in the pointer to the object.
After storing the address in the pointer to the object, the member function can be called using
the pointer to the object with the help of an arrow operator.
C++ Exception Handling
Errors are the problems that occur in the program due to an illegal operation performed by the
user or by the fault of a programmer.
Exception Handling is the process of handling errors and exceptions such that the normal
execution of the system is not halted.
Exception handling in C++ consists of three keywords namely- try, catch, and throw.
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.
Errors in C++
Errors are the problems that occur in the program due to an illegal operation performed by the
user or by the fault of a programmer, which halts the normal flow of the program.
Errors are also termed bugs or faults. There are mainly two types of errors in programming. Let
us learn about both the errors:
try {
// Block of code to try
throw exception;
}
catch () {
// Block of code to handle errors
}
Why Exception Handling?
Exception handling in C++ checks the exception so that the normal execution of the system is
not halted.
The main aim of Exception handling in c++ is to separate the error handling code from the
normal code. We can try to handle exceptions without exception handing in c++.
We can always use multiple if-else conditions to handle errors.
As normal code also contains conditional statements like if-else so, these conditions can get
mixed up with our error handling if-else conditions making the entire code less readable and
less maintainable.
So, we use try-catch blocks to easily manage exceptional handing in c++.
1) C++ try
The try block is used to keep the code that is expected to throw some exception. Whenever our
code leads to any exception or error, the exception or error gets caught in the catch block.
In simple terms, we can say that the try block is used to define the block of code that needs to
be tested for errors while it is being executed.
Example: Suppose we are dealing with databases, we should put the code that is handling the
database connection inside a try block as the database connection may raise some exceptions
or errors.
2) C++ catch
The catch block is used to catch and handle the error(s) thrown from the try block. If there are
multiple exceptions thrown from the try block, then we can use multiple catch blocks after the
try blocks for each exception.
In this way, we can perform different actions for the various occurring exceptions.
In simple terms, we can say that the catch block is used to define a block of code to be executed
if an error occurs in the try block.
3) C++ throw
The throw block is used to throw exceptions to the exception handler which further
communicates the error.
The type of exception thrown should be same in the catch block. The throw keyword accepts
one parameter which is passed to the exception handler.
We can throw both pre-defined as well as custom exception(s) as per the requirements.
Whenever we want to explicitly throw an exception, we use the throw keyword.
The throw keyword is also used to generate the custom exception.
C++ User-Defined Exceptions
The new exception can be defined by overriding and inheriting exception class functionality.
Note: In above example what() is a public method provided by the exception class. It is used to
return the cause of an exception.
Conclusion
1) Compile Time Errors are those errors that are caught during compilation time.
2) Run-Time Errors are those errors that cannot be caught during compilation time. As we cannot
check these errors during compile time, we name them Exceptions.
3) Exception Handling is the process of handling errors and exceptions such that the normal
execution of the system is not halted.
4) The main aim of Exception handling in C++ is to separate the error handling code from the
normal code.
5) Exception handling in C++ can throw both the basic data type as well as user-defined objects as
exceptions. For throwing an exception in C++, we use the throw keyword.
6) The try block is used to keep the code that is expected to throw some exception.
7) The catch block is used to catch and handle the error(s) thrown from the try block. If we have
multiple exceptions thrown from the try block, then we can use multiple catch blocks for
different exceptions.
8) The throw block is used to throw exceptions to the exception handler which further
communicates the error. The throw keyword accepts one parameter which is passed to the
exception handler.
C++ Polymorphism
The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms.
It is a greek word.
We can define polymorphism as the ability of a message to be displayed in more than one
form. In object-oriented programming, we use 3 main concepts: inheritance, encapsulation,
and polymorphism.
Polymorphism in C++ allows us to reuse code by creating one function that’s usable for
multiple uses. We can also make operators polymorphic and use them to add not only
numbers but also combine strings. This saves time and allows for a more streamlined
program.
The function to be invoked is known at the The function to be invoked is known at the run time.
compile time.
It is also known as overloading, early binding It is also known as overriding, Dynamic binding and
and static binding. late binding.
Overloading is a compile time polymorphism Overriding is a run time polymorphism where more
where more than one method is having the than one method is having the same name, number
same name but with the different number of of parameters and the type of the parameters.
parameters or the type of the parameters.
It provides fast execution as it is known at the It provides slow execution as it is known at the run
compile time. time.
It is less flexible as mainly all the things execute It is more flexible as all the things execute at the run
at the compile time. time.
1) methods,
2) constructors, and
3) indexed properties
Where the return type is the type of value returned by the function.
operator op is an operator function where op is the operator being overloaded, and the operator is
the keyword.
This is known as function overriding in C++. The function in derived class overrides the function
in base class.
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.
In the above example, pow() function is used to calculate n raised to the power p. The pow() function
is present in the math.h header file in which all the implementation details of the pow() function is
hidden.
Pure Virtual Function and Abstract Classes
Sometimes implementations of all function cannot be provided in a base class because we don’t
know the implementation. Such a class is called abstract class.
A pure virtual function is a virtual function in C++ for which we need not to write any function
definition and only we have to declare it.
It is declared by assigning 0 in the declaration. An abstract class is a class in C++ which have at
least one pure virtual function.
A virtual function is a member function in A pure virtual function is a member function in a base
a base class that can be redefined in a class whose declaration is provided in a base class and
derived class. implemented in a derived class.
The classes which are containing virtual The classes which are containing pure virtual function
functions are not abstract classes. are the abstract classes.
The base class that contains a virtual The base class that contains a pure virtual function
function can be instantiated. becomes an abstract class, and that cannot be
instantiated.
If the derived class will not redefine the If the derived class does not define the pure virtual
virtual function of the base class, then function; it will not throw any error but the derived
there will be no effect on the class becomes an abstract class.
compilation.
All the derived classes may or may not All the derived classes must define the pure virtual
redefine the virtual function. function.
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.
Files represents storage medium for storing data or information. Streams refer to sequence of
bytes.
In Files we store data i.e. text or binary data permanently and use these data to read or write
in the form of input output operations by transferring bytes of data. So we use the term File
Stream/File handling.
In C++, Files are mainly dealt by using three classes fstream, ofstream, ifstream available in
fstream headerfile.
1) ofstream: Stream class to write on files.
2) ifstream: Stream class to read from files.
3) fstream: Stream class to both read and write from/to files.
Linked List in C++ works using pointers; each node is connected to the next node using C++
pointers.
Linked List can be defined as collection of objects called nodes that are randomly stored in the
memory.
A node contains two fields i.e. data stored at that particular address and the pointer which
contains the address of the next node in the memory.
The last node of the list contains pointer to the null.
Advantages Of Linked List:
1) Dynamic data structure:
o A linked list is a dynamic arrangement so it can grow and shrink at runtime by allocating
and deallocating memory. So there is no need to give the initial size of the linked list.
2) No memory wastage:
o In the Linked list, efficient memory utilization can be achieved since the size of the linked list
increase or decrease at run time so there is no memory wastage and there is no need to
pre-allocate the memory.
3) Implementation:
o Linear data structures like stacks and queues are often easily implemented using a linked
list.
4) Insertion and Deletion Operations:
o Insertion and deletion operations are quite easier in the linked list. There is no need to shift
elements after the insertion or deletion of an element only the address present in the next
pointer needs to be updated.
Disadvantages Of Linked List:
1) Memory usage:
o More memory is required in the linked list as compared to an array. Because in a linked list,
a pointer is also required to store the address of the next element and it requires extra
memory for itself.
2) Traversal:
o In a Linked list traversal is more time-consuming as compared to an array. Direct access to
an element is not possible in a linked list as in an array by index. For example, for accessing
a node at position n, one has to traverse all the nodes before it.
3) Reverse Traversing:
o In a singly linked list reverse traversing is not possible, but in the case of a doubly-linked list,
it can be possible as it contains a pointer to the previously connected nodes with each node.
For performing this extra memory is required for the back pointer hence, there is a wastage
of memory.
4) Random Access:
o Random access is not possible in a linked list due to its dynamic memory allocation.
There are various linked list operations that allow us to perform different actions on linked
lists. For example, the insertion operation adds a new element to the linked list.
Here's a list of basic linked list operations that we will cover in this article.
1) Traversal
o access each element of the linked list
2) Insertion
o adds a new element to the linked list
3) Deletion
o removes the existing elements
4) Search
o find a node in the linked list
5) Sort
o sort the nodes of the linked list
Things to Remember about Linked List
Basic Example
#include<iostream>
class node{
public:
int data;
node* next;//pointer
//
void insertAthead(node* &head ,int val){
n->next=head;
head=n;
//1
if(head==NULL){
head=n;
return;
node* temp=head;
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=n;
}
//
//2.
node* temp=head;
while(temp!=NULL){
cout<<temp->data<<"->";
temp=temp->next;
}
cout<<"NULL"<<endl;
}
bool search(node* &
key){
node* temp=head;
while(temp!=NULL){
if(temp->data==key){
return true;
temp=temp->next;
}
return false;
}
int main(){
node* head=NULL;
insertAtTail(head,1);
insertAtTail(head,2);
insertAtTail(head,3);
display(head);
cout<<search(head,5)<<endl;
return 0;
}