Introduction To C++
Introduction To C++
INTRODUCTION
C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form programming
language that supports procedural, object-oriented, and generic programming. C++ is regarded as
a middle-level language, as it comprises a combination of both highlevel and low-level language
features. C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill,
New Jersey, as an enhancement to the C language and originally named C with Classes but later
it was renamed C++ in 1983. C++ is a superset of C, and that virtually any legal C program is a
legal C++ program. Note: A programming language is said to use static typing when type
checking is performed during compile-time as opposed to run-time.
Characteristics of C++
C++ is not a purely object-oriented language but a hybrid that contains the functionality of the C
programming language. This means that you have all the features that are available in C:
■ universally usable modular programs
■ efficient, close to the machine programming
■ portable programs for various platforms.
The large quantities of existing C source code can also be used in C++ programs. C++ supports
the concepts of object-oriented programming (or OOP for short), which are:
■ data abstraction, that is, the creation of classes to describe objects
■ data encapsulation for controlled access to object data
■ inheritance by creating derived classes (including multiple derived classes)
■ polymorphism (Greek for multiform), that is, the implementation of instructions that can have
varying effects during program execution.
Various language elements were added to C++, such as references, templates, and exception
handling. Even though these elements of the language are not strictly object-oriented
programming features, they are important for efficient program implementation
C++
OOP C
Extensions
-data abstraction -universal
-data hiding -efficient -exception handling
-inheritance -close to the machine -template
-polymorphism -portable
Traditional Procedural Programming
In traditional, procedural programming, data and functions (subroutines, procedures) are kept
separate from the data they process. This has a significant effect on the way a program handles
data:
■ the programmer must ensure that data are initialized with suitable values before use and that
suitable data are passed to a function when it is called
■ if the data representation is changed, e.g. if a record is extended, the corresponding functions
must also be modified. Both of these points can lead to errors and neither support low program
maintenance requirements
Standard Libraries
Standard C++ consists of three important parts:
The core language giving all the building blocks including variables, data types and literals,
etc.
The C++ Standard Library giving a rich set of functions manipulating files, strings, etc.
The Standard Template Library (STL) giving a rich set of methods manipulating data
structures, etc.
DATA TYPES OF C++
While writing program in any language, you need to use various variables to store various
information. Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in memory. You may like to store
information of various data types like character, wide character, integer, floating point, double
floating point, boolean etc. Based on the data type of a variable, the operating system allocates
memory and decides what can be stored in the reserved memory.
Primitive Built-in Types C++ offers the programmer a rich assortment of built-in as well as user
defined data types. Following table lists down seven basic C++ data types:
Type Keyword
Boolean bool
Character char
Integer int
Floating point float
Double floating point double
Valueless void
Wide character wchar_t
Several of the basic types can be modified using one or more of these type modifiers:
signed
unsigned
short & Long etc
VARIABLE TYPES
A variable provides us with named storage that our programs can manipulate. Each variable in
C++ has a specific type, which determines the size and layout of the variable's memory; the
range of values that can be stored within that memory; and the set of operations that can be
applied to the variable. The name of a variable can be composed of letters, digits, and the
underscore character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because C++ is case-sensitive: There are following basic types of variable in
C++ as explained
Type Description
bool Stores either value true or false.
char Typically a single octet (one byte). This is an integer type.
int The most natural size of integer for the machine.
float A single-precision floating point value.
double A double-precision floating point value.
void Represents the absence of type.
wchar_t A wide character type.
C++ also allows to define various other types of variables, which we will cover in subsequently
like Enumeration, Pointer, Array, Reference, Data structures, and Classes.
OPERATORS IN C++
An operator is a symbol used for performing operations on operands. An operator operates
operands. The operations can be mathematical or logical. There are different types of operators
in C++ for performing different operations.
Consider the following operation: z=x+y
In the above statement, x and y are the operands while + is an addition operator. When the C++
compiler encounters the above statement, it will add x and y and store the result in variable z
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators
Arithmetic Operators
They are the types of operators used for performing mathematical/arithmetic operations.
They include:
Operator Description
+ addition operator Adds to operands.
– subtraction operator Subtracts 2nd operand from 1st operand.
* multiplication operator Multiplies 2 operands.
Operator Description
/ division operator. Divides numerator by denominator.
% modulus operator Returns remainder after division.
++ increment operator Increases an integer value by 1.
— decrement operator. Decreases an integer value by 1.
for example
#include <iostream>
using namespace std;
int main() {
int a = 11;
int b = 5;
int c;
return 0;
}
Output:
Code Explanation:
1. Including the iostream header file in our code. It will allow us to read from and write to
the console.
2. Including the std namespace so as to use its classes and functions without calling it.
3. Calling the main() function inside which the logic of the program should be added. The
{ marks start of body of the main() function.
4. Declaring an integer variable a and initializing it to 11.
5. Declaring an integer variable b and initializing it to 5.
6. Declaring an integer variable c.
7. Printing value of operation a+b alongside other text on the console.
8. Printing value of operation a-b alongside other text on the console.
9. Printing value of operation a*b alongside other text on the console.
10. Printing value of operation a/b alongside other text on the console.
11. Printing value of operation a%b alongside other text on the console.
12. Printing value of operation a++ alongside other text on the console.
13. Printing value of operation a– alongside other text on the console.
14. The main() function should return an value if the program runs fine.
15. End of the body of the main() function.
Relational Operators
These types of operators perform comparisons on operands. For example, you may need to know
which operand is greater than the other, or less than the other. They include:
Operator Description
== equal to operator. Checks equality of two operand values.
!= not equal to operator Checks equality of two operand values.
> great than operator Checks whether value of left operand is greater than value of right operand.
< less than operator. Checks whether value of left operand is less than value of right operand.
>= greater than or equal to operator Checks whether value of left operand is greater than or equal to value of right operand.
<= less than or equal to operator. Checks whether value of left operand is less than or equal to value of right operand.
For example:
#include <iostream>
using namespace std;
int main() {
int a = 11;
int b = 5;
if (a < b) {
cout << "a < b is true" << endl;
}
else {
cout << "a < b is false" << endl;
}
if (a > b) {
cout << "a > b is true" << endl;
}
else {
cout << "a > b is false" << endl;
}
return 0;
}
Output:
Logical Operators
The logical operators combine two/more constraints/conditions. Logical
operators also complement evaluation of original condition under
consideration. They include:
Operator Description
&& logical AND operator. The condition is true if both operands are not zero.
! logical NOT operator. It reverses operand’s logical state. If the operand is true, the ! operator makes it false.
For example:
#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 2, c = 6, d = 4;
if (a == b && c > d)
cout << "a equals to b AND c is greater than d\n";
else
cout << "AND operation returned false\n";
if (a == b || c > d)
cout << "a equals to b OR c is greater than d\n";
else
cout << "Neither a is equal to b nor c is greater than d\n";
if (!b)
cout << "b is zero\n";
else
cout << "b is not zero";
return 0;
}
Output:
Bitwise Operators
Bitwise operators perform bit-level operations on operands. First, operators
are converted to bit level then operations are performed on the operands.
When arithmetic operations like addition and subtraction are done at bit level,
results can be achieved faster. They include:
Operator Description
It takes 2 numbers (operands) then performs AND on each bit of two numbers. If both are 1,
& (bitwise AND).
AND returns 1, otherwise 0.
Takes 2 numbers (operands) then performs OR on every bit of two numbers. It returns 1 if
| (bitwise OR)
one of the bits is 1.
Takes 2 numbers (operands) then performs XOR on every bit of 2 numbers. It returns 1
^ (the bitwise XOR)
if both bits are different.
Takes two numbers then left shifts the bits of the first operand. The second operand determines
<< (left shift)
total places to shift.
Takes two numbers then right shifts the bits of the first operand. The second operand determines
>> (right shift)
number of places to shift.
~ (bitwise NOT).
Takes number then inverts all its bits.
#include <iostream>
using namespace std;
int main() {
unsigned int p = 60; // 60 = 0011 1100
unsigned int q = 13; // 13 = 0000 1101
int z = 0;
z = p & q;
cout << "p&q is : " << z << endl; // 12 = 0000 1100
z = p | q;
cout << "p|q is : " << z << endl; // 61 = 0011 1101
z = p ^ q;
cout << "p^q is : " << z << endl; // 49 = 0011 0001
z = ~p;
cout << "~p is : " << z << endl; // -61 = 1100 0011
z = p << 2;
cout << "p<<2 is: " << z << endl; // 240 = 1111 0000
z = p >> 2;
cout << "p>>2 is : " << z << endl; // 15 = 0000 1111
return 0;
}
Output:
Assignment Operators
Assignment operators assign values to variables. The operand/variable is
added to left side of the operator while the value is added to the right side of
the operator. The variable and the value must belong to the same data type,
otherwise, the C++ compiler will raise error.
For example:
x = 5;
In the above example, x is the variable/operand, = is the assignment operator
while 5 is the value. Here are the popular assignment operators in C++:
Operator Description
= (simple assignment operator) It assigns value on the right to variable o
Operator Description
It first adds value of left operand to value
+= (Add AND assignment operator)
operand then assigns result to variable on
It first subtracts value of right operand fr
-= (Subtract AND assignment operator)
left operand then assigns result to variab
It first multiplies value of left operand w
*= (Multiply AND assignment operator) right operand then assigns result to varia
left.
It first divides value of left operand by
/= (Division AND assignment operator) value of right operand then assigns
result to variable on the left.
For example:
#include <iostream>
using namespace std;
int main()
{
int x = 5;
cout << "Initial value of x is " << x << "\n";
x += 5;
cout << "x += 5 gives :" << x << "\n";
x -= 5;
cout << "x -= 5 gives : " << x << "\n";
x *= 5;
cout << "x *= 5 gives :" << x << "\n";
x /= 5;
cout << "x /= 5 gives : " << x << "\n";
return 0;
}
Output:
C++ Identifiers
The name of a variable, function, class, or other entity in C++ is called an identifier. C++ gives you a lot
of flexibility to name identifiers as you wish.
C++ identifiers in a program are used to refer to the name of the variables, functions, arrays, or
other user-defined data types created by the programmer. They are the basic requirement of any
language. Every language has its own rules for naming the identifiers.
In short, we can say that the C++ identifiers represent the essential elements in a program which
are given below:
o Constants
o Variables
o Functions
o Labels
o Defined data types
Some naming rules are common in both C and C++. They are as follows:
For example, suppose we have two identifiers, named as 'FirstName', and 'Firstname'. Both the
identifiers will be different as the letter 'N' in the first case in uppercase while lowercase in
second. Therefore, it proves that identifiers are case-sensitive.
Types of Keywords
Data Type Keywords : These keywords are used to define the data type of
variables. Examples include int, double, and char.
Control Structure Keywords : Keywords like if, else, while, and for are used to
control the flow of a program through conditional statements and loops.
Storage Class Keywords : C++ provides keywords like static, extern, and auto
to define the storage class of variables.
Function-related Keywords : Keywords such as void, return, and class are
used to define functions and classes.
Identifiers Keywords
Identifiers are the names defined by the Keywords are the reserved words
programmer to the basic elements of a whose meaning is known by the
program. compiler.
It is used to identify the name of the It is used to specify the type of entity.
variable.
It can use both lowercase and uppercase It uses only lowercase letters.
letters.
No special character can be used except the It cannot contain any special
underscore. character.
The starting letter of identifiers can be It can be started only with the
lowercase, uppercase or underscore. lowercase letter.
Examples are test, result, sum, power, etc. Examples are 'for', 'if', 'else', 'break',
etc.
The structure of a C++ program is made up of multiple source code files that cater to different
components such as main function, member functions, class definition, headers/ standard
headers, comments, variables, data types, namespaces, input/ output statements, etc.
The c++ program is written using a specific template structure. The structure of the program
written in c++ language is as follows
DOCUMENTATION/COMMENTS
PREPROCESSOR/LINK SECTION
DEFINITION SECTION
MAIN FUNCTION
DOCUMENTATION SECTION. This section comes first and is used to document the logic of
the program that the programmer is going to code. It can also be used to write for the purpose of
the program. whatever written in the documentation section is the comment and is not compiled
by the compiler. This section is optional since the program can execute without them. comments
can be single line comments denoted with a double backward slash (//) or a multiple line
comments (/* */)
Preprocessor directives are invoked to perform various pre-processing tasks, such as importing
header files, declaring namespaces, defining constants, and other such operations that need to be
done before the program starts executing.
Header files usually contain function prototypes, class definitions, macro definitions, and other
declarations that are necessary for the program to use a particular library or API.
They are also used to define Macros and constants. Macros are defined using the #define
directive and can take arguments that are replaced by their values when macros are expanded.
#include<iostream>//importing header file. iostream handles input and output
Namespace declarations are used in defining named scopes which help in organizing and
grouping related code. It’s a way to group a set of identifiers under a common name, to avoid
naming conflicts and improve readability. They are part of the actual C++ code and are
processed by the C++ compiler during the compilation phase. Different users can create
separate namespaces thus facilitating the use of similar names for entities. This further helps in
avoiding possible compile-time errors which might arise due to identical-name conflicts.
Syntax:
this section is used to declare some constants and assign them some values. In the section, anyone can
define your own data type using the primitive data types
Global variables
Global variables are variables that are declared outside of any function or class and are
accessible from any part of the program.
It’s generally considered good practice to minimize the use of global variables. This is because a
program/ structure with variables (global) is harder to read, understand and debug. So they must
be used judiciously and with great care, whenever necessary.
1
8
#include<iostream>
int main()
Output:
The main function is the entry point or the startup function for every C++ program, i.e. this
section defines the main() function of the program. This is where the program starts executing,
hence this section is a mandatory part of the structure of the C++ program.
Besides the function declaration and program execution, the return type of the main function is
also mentioned in this section. All in all, the main function coordinates the flow of the entire
program by calling other functions, handles user input and output, and performs various other
tasks.
4
5
10
#include<iostream> //importing header file. iostream handles input and output streams
int main()
Output:
hello world
CONTROL STRUCTURES
A control structure is a programming component that analyzes variables and makes a decision in which
direction execution should go, based on given parameters. There are three (3) basic control structures
used for program development in almost all modern programming languages, including C++. These are,
sequence, selection and iteration/looping
Sequence :- In computer programming, sequence is the default control structure, since instructions are
executed one after another. These instructions might, for example, carry out a series of arithmetic
operations, assign results to variables, find the roots of a quadratic equation, etc.
Selection
Simple IF Statement: The if statement evaluates a logical expression, and performs one or more
executable statement(s), or transfers control to an optional else statement, or even terminate the if
statement, depending on the (truth) value of the logical expression. The syntax for different variants of
the if statement is given below:
end if
if <condition> then
block of statements
else
block of statements
Iteration
FOR construct
Do while construct
while construct
In C++, for loop is an entry-controlled loop that is used to execute a block of code repeatedly for the
specified range of values. Basically, for loop allows you to repeat a set of instructions for a specific
number of iterations.
for loop is generally preferred over while and do-while loops in case the number of iterations is known
beforehand.
C++ STREAMS
C++ is the top choice of many programmers for creating powerful and scalable applications.
From operating systems to video games, C++ is the proven language for delivering high-
performance solutions across a range of industries.
One of the standout features of C++ is its built-in support of streams. C++ makes it easy to
channel data in and out of your programs like a pro. Whether you’re pushing data out
to cout or pulling it in from cin, C++ streams are the key to keeping your code in the zone.
In this blog post, we’re going to take you on a deep dive into the world of C++ streams. So
buckle up, grab your coffee, and get ready to level up your programming skills!
What are C++ streams?
In C++, a stream refers to a sequence of characters that are transferred between the program
and input/output (I/O) devices. Stream classes in C++ facilitate input and output operations on
files and other I/O devices. These classes have specific features to handle program input and
output, making it easier to write portable code that can be used across multiple platforms.
To use streams in C++, you need to include the appropriate header file. For instance, to use
input/output streams, you would include the iostream header file. This library provides the
necessary functions and classes to work with streams, enabling you to read and write data to
and from files and other I/O devices. We’ll be exploring four essential C++ stream classes:
1. istream
2. ostream
3. ifstream
4. ofstream
Object-oriented programming, such as C++, relies heavily on the concept of inheritance.
Inheritance allows a class to inherit properties from another class that has already been defined.
Descendant classes can then add their own unique properties, making them specializations of
their parent class.
Take the stream class hierarchy as an example. In the diagram below (only a portion is shown),
we can see that ifstream is a specialization of istream. This means that an ifstream object is
an istream object and inherits all the properties of the istream class. Additionally, it adds some
additional properties of its own.
The C++ stream class hierarchy consists of a number of classes that define and provide
different flows for objects in the class. The hierarchy is structured in a way that starts with the
top class, which is the ios class, followed by other classes such as the istream, ostream,
iostream, istream_withassign, and ostream_withassign classes.
The ios class is the parent class in the hierarchy and both the istream and ostream classes
inherit from it. These two classes together form the ios class, which is the highest level of the
entire C++ stream class hierarchy.
Other classes in the hierarchy provide functions for various operations, including assignment
operations, such as the _withassign classes.
Let’s deep dive into the four essential stream classes:
1. The istream class
This class is a general-purpose input stream and is used to read input from various sources,
including the console and files. One example of an istream is cin, which is a commonly used
input stream for reading input from the console. The istream class provides a range of
functions for handling characters, strings, and objects,
including get, getline, read, ignore, putback, and cin.
These functions enable developers to manipulate input in various ways. For example, the get
function allows developers to read a single character from the input stream, while
the getline function reads an entire line of text and stores it in a string object. The read function
is used to read a specific number of characters from the input stream and store them in a buffer.
Overall, the istream class is an essential component of input stream handling in C++.
1 #include <iostream>
3 int main()
4 {
5 char a;
6 cin.get(a);
7 cout << a;
8 return 0;
9 }
3 intmain()
4 {
5 char u;
6 cin.get(u);
7 cout.put(u);
8 }
2 fout << "The minimum oxygen percentage is " << minO2 << endl;
C++ streams are used in a wide variety of applications, from simple console programs to
complex software systems. Some common use cases for C++ streams include:
1. Reading and writing to files – C++ streams provide a convenient way to read and write
data to and from files. This can be used to create log files, read configuration files, and
more.
2. Parsing input – C++ streams can be used to parse input data, such as reading data from
a CSV file or parsing command-line arguments.
3. Debugging – C++ streams can be used to output debugging information, such as the
value of variables, to the console or a file.
4. Network programming – C++ streams can be used to read and write data over a
network connection, such as when creating a client-server application.
In summary, C++ streams are a powerful feature of the C++ programming language and
provide a standardized way to handle input and output. You can read and write data to and
from a variety of sources, including files, input/output devices, and even other programs. By
understanding the syntax and functionality, you can write more efficient and portable code that
can be used across multiple platforms.
C++ MULTIPLE, MULTILEVEL AND HIERARCHICAL INHERITANCE
Inheritance is one of the core feature of an object-oriented programming language. It allows software
developers to derive a new class from the existing class. The derived class inherits the features of the
base class (existing class).
In C++ programming, not only you can derive a class from the base class but you can also derive a class
from the derived class. This form of inheritance is known as multilevel inheritance.
class A {
... .. ...
};
class B: public A {
... .. ...
};
class C: public B {
};
Here, class B is derived from the base class A and the class C is derived from the derived
class B .
Example 1: C++ Multilevel Inheritance
#include <iostream>
using namespace std;
class A {
public:
void display() {
cout<<"Base class content.";
}
};
int main() {
C obj;
obj.display();
return 0;
}
Output
In this program, class C is derived from class B (which is derived from base class A).
The compiler first looks for the display() function in class C. Since the function doesn't exist there, it
looks for the function in class B (as C is derived from B).
The function also doesn't exist in class B, so the compiler looks for it in class A (as B is derived from A).
If display() function exists in C, the compiler overrides display() of class A (because of member function
overriding).
In C++ programming, a class can be derived from more than one parent. For example, A class Bat is
derived from base classes Mammal and WingedAnimal. It makes sense because bat is a mammal as well
as a winged animal.
Multiple Inheritance
#include <iostream>
using namespace std;
class Mammal {
public:
Mammal() {
cout << "Mammals can give direct birth." << endl;
}
};
class WingedAnimal {
public:
WingedAnimal() {
cout << "Winged animal can flap." << endl;
}
};
int main() {
Bat b1;
return 0;
}
Output
Suppose, two base classes have a same function which is not overridden in derived class.
If you try to call the function using the object of the derived class, compiler shows error. It's because
compiler doesn't know which function to call. For example,
class base1 {
public:
void someFunction( ) {....}
};
class base2 {
void someFunction( ) {....}
};
class derived : public base1, public base2 {};
int main() {
derived obj;
obj.someFunction() // Error!
}
This problem can be solved using the scope resolution function to specify which function to class
either base1or base2
int main() {
For example, Physics, Chemistry, Biology are derived from Science class. Similarly, Dog, Cat, Horse are
derived from Animal class.
Syntax of Hierarchical Inheritance
class base_class {
... .. ...
... .. ...
... .. ...
... .. ...
#include <iostream>
using namespace std;
// base class
class Animal {
public:
void info() {
cout << "I am an animal." << endl;
}
};
// derived class 1
class Dog : public Animal {
public:
void bark() {
cout << "I am a Dog. Woof woof." << endl;
}
};
// derived class 2
class Cat : public Animal {
public:
void meow() {
cout << "I am a Cat. Meow." << endl;
}
};
int main() {
// Create object of Dog class
Dog dog1;
cout << "Dog Class:" << endl;
dog1.info(); // Parent Class function
dog1.bark();
// Create object of Cat class
Cat cat1;
cout << "\nCat Class:" << endl;
cat1.info(); // Parent Class function
cat1.meow();
return 0;
}
Output
Dog Class:
I am an animal.
I am a Dog. Woof woof.
Cat Class:
I am an animal.
I am a Cat. Meow.
Here, both the Dog and Cat classes are derived from the Animal class. As such, both the derived
classes can access the info() function belonging to the Animal class.
C and C++ support pointers, which is different from most other programming languages such as
Java, Python, Ruby, Perl and PHP as they only support references. But interestingly, C++, along
with pointers, also supports references.
On the surface, both references and pointers are very similar as both are used to have one
variable provide access to another. With both providing lots of the same capabilities, it’s often
unclear what is different between these mechanisms. In this article, I will try to illustrate the
differences between pointers and references. nt i = 3;
References and pointers are two very important concepts for those who want to write efficient,
correct code, we will discuss the difference between pointer and reference in C++ in complete
detail to help you understand the nuances and write better codes. But first, let's take a look at the
basics of the concepts themselves.
What is Reference?
A reference is an alias for an already existing variable. After the reference variable is initialized,
it is possible to use a reference name to refer to that variable. Reference in C++ is created by
storing the address of another variable. A reference variable can be considered a constant
pointer with automatic indirection, i.e., the compiler will apply an indirection operator (*) for
you. The declaration of a reference variable contains the base type followed by the ‘&’ sign and
then the variable name.
#include <iostream>
int main(){
return 0;
}
Output:
The value of temp is: 10;
Explanation:
We started by declaring the header file, then moved to the main function.
In the main function, we first declare an int variable temp and assign it a value of 10.
In the next line, when we print the value of 'a', it shows the value of the variable where it
is referencing.
What is Pointer?
A pointer is a programming language object that stores the address of another variable. In other
words, it stores the direct address of the memory location. A pointer should also be declared
before it is used, unlike other variables. It can be dereferenced with the help of the '*' operator to
access the memory location to which the pointer points.
The size of the int pointer is 4 bytes. (which can be determined using the operation sizeof())
The declaration of the pointer variable contains the base data type followed by the ‘*’ sign. For
example,
int *a; //
Here we use a '*' operator for defining a pointer
Code Example
#include <iostream>
int main(){
int temp = 10; //initializing temp named variable
return 0;
}
Output:
Explanation:
We started by declaring the header file, then move to the main function.
In the main function, we first declare an int variable temp and assign it a value of 10.
Then we create a pointer variable 'ptr', which stores/points to the address of the temp
variable (i.e., we have used &temp, which indicates the address of the temp variable).
In the next line, when we print the value of 'ptr', it shows the value of the variable where
it is pointing.
Reference Pointers
This variable is referenced by the The pointer does it work by the method
method pass-by-value.
known as pass-by-reference.
Some of the key differences between Pointers and references are given below-
1. Methos of Initialization
int a = 10;
int *ptr;
ptr = &a;
The way to initialize the reference variable is as shown below-
int a = 10;
int &ref = a;
2. Functionality
A pointer holds the address of the variable to which it is pointing to, while a reference variable
is an alias for a variable that already exists.
3. Operator
The pointer operator, i.e., the operator used to declare the pointer is the star operator (*), while
the reference operator is an ampersand, i.e., (&).
int *ptr = &a; // use the * operator for declaring the pointer in C++
int a = 10;
4. Null value
In C++, we can have a NULL pointer, which can be used in logical operations. However, we
cannot have NULL references.
Code Example:
#include<stdio.h>
int main(){
return 0;
}
Output:
5. Memory Address
A pointer has its own memory address and size in the stack. In contrast, a reference does not
have its own separate memory location. Instead, it shares with the variable memory only but
takes some space on the stack.
Example:
int *ptr = a;
Explanation:
The first line will print the address of the pointer, while the other line prints the address of the
variable. You will observe that both addresses are different
6. Dereferencing
A pointer variable can be dereferenced with the help of the '*' operator. In contrast, the reference
variable requires no operator for dereferencing. This is because it can be used like a normal
variable.
7. Reassignments
Reassignment is the property of a variable to reassign its value again. A pointer can be re-
assigned, i.e., a pointer can be re-assigned again to a different variable. This property of the
pointer makes it useful in many data structures, such as a Linked list, trees, etc.
Code Example:
#
main(){
int a = 10;
int b = 20;
return 0;
}
Output:
Initially, we started the code by including the header file, and then we start the main
function.
We declare and initialize an int variable 'a' and assign it a value of 10.
Using the cout statement, we print the value of the pointer, which came out to be 10.
Then again, we declare and initialize a different variable b, and assign a value of 20.
Next, we create a pointer that points to b, and using the cout statement, we print the
value of the pointer again, which comes out to be 20.
So we can see that we can re-assigned the value of the pointer. While on the other hand,
references cannot be re-assigned. That is, it has to be assigned at the time of initialization only.
Example:
int a =10;
int &ref = a;
int b = 20;
int &ref = b; // this line will throw an error stating "Multiple declarations is not allowed"
The example above throws the error as the reassignment operation is not valid in references.
8. Arithmetic operations
Various arithmetic operations can be performed on the pointer, which is also known as pointer
arithmetic. For example, increment/decrement, addition, subtraction, etc. But there are no such
arithmetic operations in reference.
9. Indirection
You can have multiple levels of indirection in a pointer, such as a pointer to a pointer (known as
a double pointer) and others. In contrast, references only offer one level of indirection.
#include<stdio.h>
using namespace std;
int main(){
int a = 10;
int *ptr = &a;
int **ptr2 = &ptr;
return 0;
}
Code Explanation:
Here, we first declare a pointer name as ptr and assign it to a. Then, we declare a pointer to the
pointer which is ptr2 which is pointing to ptr. This is known as the level of indirection.
10. Usage
Pointer variables should be used when the possibility of referring to nothing exists or when it is
required to refer to different things at different times. In comparison, the usage of references is
valid only when there is any object to refer to.
11. Application/ Use Cases
The concept of pointer needs to be understood completely before using the data structures such
as linked lists, trees, etc.
A reference variable can be used in the function parameters, function return value, and return
type to define user interfaces. In many cases, it can be used as an alternative to a pointer also.
NULL declaration: Reference cannot be NULL, unlike a pointer, which can have a
NULL value. Null pointers indicate that they are pointing to nothing, which is helpful in
many cases.
Initialization: A reference variable has to be initialized and declared at the same time.
Reassignment: Unlike pointers, reference variables cannot reassign to a new value after
they have been declared.
In the end, we come to conclude that the pointer and reference are related to dynamic memory
allocation in C++. The main difference between the both is that the pointer holds the address of
another variable to which it is pointing to, while the reference is just an alias to access the
existing variable.
Secondly, we can conclude that references are less powerful as compared to pointers but are
easy and safer to use than pointers
There are three parameter-passing modes in C++: by value, by pointer, and by reference.
When a parameter is passed by value, the changes made to the parameter within the function do
not affect the value of the actual argument used in the function call. When a parameter is passed
by pointer or by reference, changes made to the parameter do affect the actual arguments in the
client space. In addition, there is a special mode of passing array parameters.
We will consider different modes of parameter passing, their syntax, and their semantics, and we
will try to formulate guidelines for the use of C++ parameter-passing modes that provide the best
performance and the best transmission of designer ideas to the maintenance ...
In C++, data must be sent to functions when they are called in order to perform operations. This
data is called parameters or arguments and there are various parameter passing methods available
in C++, each with merits and demerits of its own. In this article, we will discuss various
parameter-passing techniques in C++.
BASIC TERMINOLOGIES
Actual Parameters (also known as arguments) are the values that are being passed to the
function. These variables, which indicate the data that the function anticipates receiving when
called, are specified in the parameter list of a function
Formal Parameters are the variables that are defined in the function definition. : The
expressions or values passed in during a function call. When the function is called, it receives
1. Pass by Value
In Pass by Value method, a variable’s actual value is copied and then passed to the function
instead of the original variable. As the result, any changes to the parameter inside the function
will not affect the variable’s original value outside the function. Although it is easy to understand
and implement, this method is not so useful for large size of data structures at it involves copying
the value.
Example
C++
#include <iostream>
int temp = a;
a = b;
b = temp;
int main()
int x = 5;
int y = 10;
cout << "Before Swapping:\n";
cout << "x = " << x << ", y = " << y << endl;
// parameters
swap(x, y);
cout << "x = " << x << ", y = " << y << endl;
return 0;
Output
Before Swapping:
x = 5, y = 10
After Swapping:
x = 5, y = 10
2. Pass by Reference
In pass-by-reference method, instead of passing the argument itself, we passes the reference of
an argument to the function. This allows the function to change the value of the original
argument.
Any changes we make to your argument inside your function are reflected in your original
argument so we have to be careful while handling data in this method.
Example
C++
#include <iostream>
int temp = a;
a = b;
b = temp;
}
// driver code
int main()
int x = 5;
int y = 10;
swap(x, y);
Output
Before swap:
x = 5, y = 10
After swap:
x = 10, y = 5
3. Pass by Pointer
The pass-by-pointer is very similar to the pass-by-reference method. The only difference is that
we pass the raw pointers instead of reference to the function. It means that we pass the address of
the argument to the function.
Example
C++
#include <iostream>
{
int temp = *a;
*a = *b;
*b = temp;
// driver code
int main()
int x = 5;
int y = 10;
swap(&x, &y);
return 0;
Output
Before swap:
x = 5 ,y = 10
After swap:
x = 10 ,y = 5