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

Unit-3 c++

Unit 3 c++

Uploaded by

akshatshahi815
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Unit-3 c++

Unit 3 c++

Uploaded by

akshatshahi815
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Unit -3

Pointer:- Pointers are variables that contain the memory address of another variable
instead of a direct value. Such variables can be of type. int, float, char, etc.
By referencing this memory address, programmers can access and modify data
indirectly.
Syntax:
datatype *var_name;
int *ptr; // ptr can point to an address which holds int data

Use of Pointers in C++


 Dynamic memory allocation - In the C++ programming language, the
programmers can dynamically allocate memory by using
the malloc() and calloc() functions, mainly where the pointer is used. This is the
primary use of pointers in C++.
 Arrays, Functions, and Structures - Pointers in the c ++ programming language
are widely used in arrays, structures, and functions. It reduces the code and improves
the performance of that particular program.

C++ Pointer Declaration


Pointer variables are declared like normal variables except for the addition of the
unary ∗ character.

The general form of a pointer declaration is as follows:


type ∗var_name;

where "type" can be any valid C++ data type, and "var_name" is the name of the
pointer variable. The following declarations declare pointers of different types:
int ∗iptr; // creates an integer pointer iptr
char ∗cptr; // creates a character pointer cptr
float ∗fptr; // creates a float pointer fptr
When we say that "iptr" is an integer pointer, it means that the memory location being
pointed to by iptr can hold only integer values. In other words, it can be stated that iptr
is a pointer to an integer.

wo special operators, ∗ and &, are used with pointers. The "&" operator is a unary
operator that returns the operand's memory address. For example,
int i = 100; // declares an int variable i
int *iptr; // declares an int pointer iptr
iptr = &i; // stores the memory address of i into iptr
In the above-given three statements, the first statement is:
int i = 100;

declares an integer pointer and initializes a value of "100" to it. Then comes the
second statement, which is:
int *iptr;

declares an integer pointer named "iptr." Finally, using the third and last statement,
which is:
iptr = &i;

Pointer Initialization in C++


The procedure of initializing a pointer is where we give the memory address of another
variable using the & (address of) operator.
#include <iostream>
using namespace std;
int main() {
int x = 42; // Declare and initialize an integer variable 'x'
// declare pointer variable 'ptr' and initialize it with the address of 'x'
int *ptr = &x;
// print value of x
cout << "x = " << x << endl;
// print address of x
cout << "Address of x (&x) = " << &x << endl
<< endl;
// print pointer ptr
cout << "ptr = " << ptr << endl;
// print the content of the address ptr points to
cout << "Content of the address pointed to by ptr (*ptr) = " << *ptr << endl;

return 0;
}
Output
x = 42
Address of x (&x) = 0x7ffeb5f7b3c4

ptr = 0x7ffeb5f7b3c4
Content of the address pointed to by ptr (*ptr) = 42
References
A reference variable is an alias, that is, another name for an already existing variable. Once a
reference is initialized with a variable, either the variable name or the reference name may be used to
refer to the variable.

References vs Pointers
References are often confused with pointers but three major differences between references and
pointers are −

 You cannot have NULL references. You must always be able to assume that a reference is
connected to a legitimate piece of storage.
 Once a reference is initialized to an object, it cannot be changed to refer to another object.
Pointers can be pointed to another object at any time.
 A reference must be initialized when it is created. Pointers can be initialized at any time.

Creating References in C++


Think of a variable name as a label attached to the variable's location in memory. You can then think
of a reference as a second label attached to that memory location. Therefore, you can access the
contents of the variable through either the original variable name or the reference. For example,
suppose we have the following example −

int i = 17;

We can declare reference variables for i as follows.

int& r = i;

Read the & in these declarations as reference. Thus, read the first declaration as "r is an integer reference
initialized to i" and read the second declaration as "s is a double reference initialized to d.". Following
example makes use of references on int and double −

#include <iostream>
using namespace std;
int main ()
{
// declare simple variables
int i;
double d;
// declare reference variables
int& r = i; double& s = d; i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl; d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl; return 0; }
return 0;
}
TYPES OF POINTER
1)void Pointer in C++
n C++, a void pointer is a pointer that is declared using the 'void' keyword (void*). It
is different from regular pointers it is used to point to data of no specified data type.
It can point to any type of data so it is also called a "Generic Pointer".
Syntax of Void Pointer in C++
void* ptr_name;
As the type of data the void pointer is pointing to is unknown, we cannot
dereference a void pointer.

Example of Void Pointer in C++


The below example demonstrates the declaration and use of void pointer in C++.
C++
// C++ Program to demonstrate the declaration and use of a
// void pointer

#include <iostream>
using namespace std;

int main()
{
int a = 10;

// void pointer holds address of int 'a'


void* myptr = &a;
// printing the value of a and adress of a stored in
// myptr
cout << "The value of a is: " << a << endl;
cout << "The Adress of a is " << myptr << endl;
}

Output
The value of a is: 10
The Adress of a is 0x7ffd9ac02a64
2)NULL POINTER
A NULL Pointer in C++ indicates the absence of a valid memory address in C++. It
tells that the pointer is not pointing to any valid memory location In other words, it
has the value "NULL" (or 'nullptr' since C++11). This is generally done at the time
of variable declaration to check whether the pointer points to some valid memory
address or not. It is also returned by several inbuilt functions as a failure response.
Trying to dereference a NULL pointer i.e. trying to access the memory it points to
leads to some undefined behavior leading to the program crash.
Syntax of Null Pointer in C++
We can create a NULL pointer of any type by simply assigning the value NULL to
the pointer as shown:
int* ptrName = NULL; // before C++11

int* ptrName = nullptr

int* ptrName = 0; // by assigning the value 0


A null pointer is represented by the value 0 or by using the keyword NULL. With
the new versions of C++ like C++11 and later, we can use "nullptr" to indicate a null
pointer.
Checking NULL Pointer
We can check whether a pointer is a NULL pointer by using the equality comparison
operator.
ptrName == NULL
or
ptrName == nullptr
The above expression will return true if the pointer is a NULL pointer. False
otherwise.
Applications of Null Pointer in C++
Null Pointer finds its applications in the following scenarios:
1. Initialization: It is a good practice to Initialize pointers to a null value as it helps
avoid undefined behavior by explicitly indicating they are not pointing to valid
memory locations.
2. Default Values: Null pointers act as default or initial values for pointers when no
valid address is assigned to the pointers.
3. Error Handling: They are useful in error conditions or to signify the absence of
data that enables better handling of exceptional cases.
4. Resource Release: To release the resources, like the destructor of a class, or to
set pointers to NULL after deletion we can use a null pointer to avoid
accidentally using or accessing the released memory.
5. Sentinel Values: A null pointer can be used to indicate the end of a data structure
or a list like in the linked list last node has a null pointer as the next field.

// C++ program to demonstrate the dereferencing and


// assignment of null pointer to another value.
1.
2. #include <iostream>
3. using namespace std;
4.
5. int main()
6. {
7. int* ptr = nullptr;
8.
9. // Checking if the pointer is null before dereferencing
10. if (ptr == nullptr) {
11. cout << "Pointer is currently null." << endl;
12. }
13. else {
14. cout << "Pointer is not null." << endl;
15. }
16.
17. // *ptr = 10; (to avoid runtime error)
18.
19. // Assigning a valid memory address to the pointer
20. int value = 5;
21. ptr = &value;
22.
23. // Checking if the pointer is null after assigning a
24. // valid address
25. if (ptr == nullptr) {
26. cout << "Pointer is currently null." << endl;
27. }
28. else {
29. cout << "Pointer is not null." << endl;
30. cout << "Value at the memory location pointed to "
31. "by the pointer: "
32. << *ptr << endl;
33. }
34.
35. return 0;
36. }
37.
Output
38. Pointer is currently null.
39. Pointer is not null.
40. Value at the memory location pointed to by the pointer: 5

3)Dangling Pointers in C++



In C++, pointers can be used for various purposes such as storing the address of a variable,
allocated objects on the heap, passing functions to other functions, iterating over elements in
arrays, and so on. But many problems arise when pointers are not handled properly. In this
article, we will learn about dangling pointers, how they occur and how to deal with them.
What is a Dangling Pointer in C++?
In C language, a pointer that points to a memory location that has been deallocated earlier in
the program is called Dangling Pointer.
A dangling pointer is a very common occurrence that generally occurs when we use the 'delete'
to deallocate memory that was previously allocated and the pointer that was pointing to that
memory still points to the same address. There are also other cases which leads to the pointer
being the dangling pointer:
Cases that Leads to Dangling Pointer in C++
 Deallocation of Memory using delete or free().
 Referencing the Local Variable of the function after it is executed.
 Variable goes out of scope.
For Example
int* ptr = new int(5);
delete ptr; // ptr now becomes a dangling pointer
Examples of Dangling Pointer in C++
Example 1: Dangling Pointer by Memory Deallocation using delete.
The below program demonstrates how a pointer becomes a dangling pointer when the
dynamic memory is deallocated using delete or in C++.
// C++ program demonstrating how a dangling pointer is
// created
#include <iostream>
using namespace std;

int main()
{
// Allocating memory
int* ptr = new int(5);

// Deallocating memory
delete ptr;

// Now, ptr becomes a dangling pointer


cout << "ptr is now a dangling pointer" << endl;

return 0;
}

Output
ptr is now a dangling pointer

Example 2: Dangling Pointer Created by Accessing Variable Out of


Scope.
C++

// C++ program to demonstrate how the accessing a variable


// outisde its scope results in dangling pointer
#include <stdio.h>
int main()
{
int* danglingPtr;

// block scope
{
int var = 210;
danglingPtr = &var;
}
// Undefined behavior
printf("Value of dangling pointer: %d\n", *danglingPtr);
return 0;
}

The above program will lead to undefined behaviour or segmentation fault or you
can also get the value of the variable. It is unpredictable.
4) Wild Pointers
What are Wild Pointers? How can we avoid?
Uninitialized pointers are known as wild pointers because they point to some arbitrary
memory location and may cause a program to crash or behave unexpectedly.
// C program that demonstrated wild pointers
int main()
{
/* wild pointer */
int* p;
/* Some unknown memory location is being corrupted.
This should never be done. */
*p = 12;
}

How can we avoid wild pointers?


If a pointer points to a known variable then it’s not a wild pointer.
Example
In the below program, p is a wild pointer till this points to a.
C
int main()
{
int* p; /* wild pointer */
int a = 10;
/* p is not a wild pointer now*/
p = &a;
/* This is fine. Value of a is changed */
*p = 12;
}

If we want a pointer to a value (or set of values) without having a variable for the
value, we should explicitly allocate memory and put the value in the allocated
memory.
Example
C
int main()
{
int* p = (int*)malloc(sizeof(int));
// This is fine (assuming malloc doesn't return
// NULL)
*p = 12;
}
this’ pointer
In C++, ‘this’ pointers is a pointer to the current instance of a class. It is used to
refer to the object within its own member functions. In this article, we will learn how
to use ‘this’ pointer in C++.

EX:- #include <iostream>


using namespace std;

// Class that uses this pointer


class A {
public:
int a;
A(int a) {

// Assigning a of this object to


// function argument a
this->a = a;
}
void display() {

// Accessing a of this object


cout << "Value: " << this->a;
}
};

int main() {

// Checking if this works for the object


A o(10);
o.display();

return 0;
}

Output
Value: 10

Understanding this Pointer


To understand ‘this’ pointer, it is important to know how objects look at functions
and data members of a class.
1. Each object gets its own copy of the data member.
2. All-access the same function definition as present in the code segment.
What is a Pointer to an object?
A pointer to an object in C++ is a variable that contains an object's memory address. Pointers
provide indirect access to and control over memory items. They are especially helpful when we need
to dynamically allocate memory for objects, build linked lists or trees, or pass objects by reference to
methods without making duplicates.
The behavior of an object pointer is identical to that of a variable pointer. But in this case,
the object's address is kept instead of the variables. When a class object is formed in the main
function, a pointer variable is declared similarly to the variable itself. Using a data type for
the pointer is not recommended when generating a pointer to an object. Instead, we must make use of
the object pointer's class name. The -> symbol must be used to call a class member function using a
Pointer in the main function.
Syntax:
It has the following syntax:
Declaring a Pointer to an Object:
We declare a pointer to an object using the object's class name followed by an asterisk (*) and
the pointer name.
1. ClassName *pointer name; // Declaration of a pointer to an object
Test it Now

The pointer of Base Class pointing different objects of the derived


classExample:
C++
// C++ program to Demonstrate the
// implementation of the base class
// pointer pointing to derived class
#include <iostream>
using namespace std;
// Base Class
class BaseClass {
public:
int v1;
// Function to display the base
// class members
void display()
{
cout << "Displaying Base class"<< " variable var_base: " << v1 << endl;
}
};

// Class derived from the Base Class


class DerivedClass : public BaseClass {
public:
int v2;

// Function to display the base


// and derived class members
void display1()
{
cout << "Displaying Base class"<< "variable var_base: " <<v2 << endl;

}
};

// Driver Code
int main()
{
BaseClass B1*;
B1->v1=10;
DerivedClass D1;
B1= &D1;
B1->v2=100;

B1->display1();
B1->display();

return 0;
}
new and delete Operators in C++ For Dynamic
Memory

Dynamic memory allocation in C/C++ refers to performing memory allocation


manually by a programmer. Dynamically allocated memory is allocated on Heap, and
non-static and local variables get memory allocated on Stack
How is memory allocated/deallocated in C++?

C uses the malloc() and calloc() function to allocate memory dynamically at run
time and uses a free() function to free dynamically allocated memory. C++ supports
these functions and also has two operators new and delete, that perform the task of
allocating and freeing the memory in a better and easier way.

1. new operator
The new operator denotes a request for memory allocation on the Free Store. If
sufficient memory is available, a new operator initializes the memory and returns the
address of the newly allocated and initialized memory to the pointer variable.
Syntax to use new operator
pointer-variable = new data-type;

Example: 1.
// Pointer initialized with NULL
// Then request memory for the variable
int *p = NULL;
p = new int;

OR

// Combine declaration of pointer


// and their assignment
int *p = new int;

Example: 2
// C++ program to demonstrate how to create dynamic variable
// using new
#include <iostream>
#include <memory>
using namespace std;

int main()
{
// pointer to store the address returned by the new
int* ptr;
// allocating memory for integer
ptr = new int;

// assigning value using dereference operator


*ptr = 10;
// printing value and address
cout << "Address: " << ptr << endl;
cout << "Value: " << *ptr;

return 0;
}

Output
Address: 0x162bc20
Value: 10

Example: 3
#include<iostream>
using namespace std;
int main() {
int x, n;
cout << "Enter the number of items:" << "\n";
cin >>n;
int *arr = new int[n];
cout << "Enter " << n << " items" << endl;
for (x = 0; x < n; x++) {
cin >> arr[x];
}
cout << "You entered: ";
for (x = 0; x < n; x++) {
cout << arr[x] << " ";
}
return 0;
}
Output:

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

Example:
// It will free the entire array
// pointed by p.
delete[] p;
Constructor

Constructor in C++ is a special method that is invoked automatically at the time an


object of a class is created. 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. It
constructs the values i.e. provides data for the object which is why it is known as a
constructor.

Syntax of Constructors in C++


The prototype of the constructor looks like this:
<class-name> (){
...
}
Characteristics of Constructors in C++
 The name of the constructor is the same as its class name.
 Constructors are mostly declared in the public section of the class though they
can be declared in the private section of the class.
 Constructors do not return values; hence they do not have a return type.
 A constructor gets called automatically when we create the object of the class.

Ex:-1 Constructor within Class


// Example to show defining
// the constructor within the class

#include <iostream>
using namespace std;

// Class definition
class student {
int rno;
char name[50];
double fee;

public:
/*
Here we will define a constructor
inside the same class for which
we are creating it.
*/
student()
{
// Constructor within the class

cout << "Enter the RollNo:";


cin >> rno;
cout << "Enter the Name:";
cin >> name;
cout << "Enter the Fee:";
cin >> fee;
}

// Function to display the data


// defined via constructor
void display()
{
cout << endl << rno << "\t" << name << "\t" << fee;
}
};

int main()
{

student s;
/*
constructor gets called automatically
as soon as the object of the class is declared
*/

s.display();
return 0;
}

Ex:-2 Constructor outside Class


// defining the constructor outside the class
#include <iostream>
using namespace std;
class student {
int rno;
char name[50];
double fee;

public:
/*
To define a constructor outside the class,
we need to declare it within the class first.
Then we can define the implementation anywhere.
*/
student();

void display();
};

/*
Here we will define a constructor
outside the class for which
we are creating it.
*/
student::student()
{
// outside definition of constructor
cout << "Enter the RollNo:";
cin >> rno;
cout << "Enter the Name:";
cin >> name;
cout << "Enter the Fee:";
cin >> fee;
}

void student::display()
{
cout << endl << rno << "\t" << name << "\t" << fee;
}

// driver code
int main()
{
student s;
/*
constructor gets called automatically
as soon as the object of the class is declared
*/

s.display();
return 0;
}

Output:
Enter the RollNo:11
Enter the Name:Aman
Enter the Fee:10111
11 Aman 10111
Types of Constructors in C++
Constructors can be classified based on in which situations they are being used.
There are 4 types of constructors in C++:
1. Default Constructor: No parameters. They are used to create an object with
default values.
2. Parameterized Constructor: Takes parameters. Used to create an object with
specific initial values.
3. Copy Constructor: Takes a reference to another object of the same class. Used
to create a copy of an object.
4. Constructor Overloading: Overloaded constructors essentially have the same
name (exact name of the class) and different by number and type of arguments.

Default Constructor
A default constructor is a constructor that doesn’t take any argument. It has no
parameters. It is also called a zero-argument constructor.
Syntax of Default Constructor
className() {
// body_of_constructor
}
The compiler automatically creates an implicit default constructor if the programmer
does not define one.

EX:-
#include <iostream> Output :-
using namespace std;
class Employee Default Constructor Invoked
{
public: Default Constructor Invoked
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}

2. Parameterized Constructor
Parameterized constructors make it possible to pass arguments to constructors.
Typically, these arguments help initialize an object when it is created. To create a
parameterized constructor, simply add parameters to it the way you would to any
other function. When you define the constructor’s body, use the parameters to
initialize the object.
Syntax of Parameterized Constructor
className (parameters...) {
// body
}

Example

#include <iostream>
using namespace std;
class A {
private:
int num1, num2 ;
public:
A(int n1, int n2) {
num1 = n1;
num2 = n2;
}
void display() {
cout<<"num1 = "<< num1 <<endl;
cout<<"num2 = "<< num2 <<endl;
}
};
int main() {
A obj(3,8);
obj.display();
return 0;
}

Output
num1 = 3
num2 = 8

3. Copy Constructor
A copy constructor is a member function that initializes an object using another
object of the same class.
Syntax of Copy Constructor
Copy constructor takes a reference to an object of the same class as an argument.
ClassName (ClassName &obj)
{
// body_containing_logic
}

Ex:-
#include <iostream>
using namespace std;
class A
{
public:
int x;
A(int a) // parameterized constructor.
{
x=a;
}
A(A &i) // copy constructor
{
x = i.x;
}
};
int main()
{
A a1(20); // Calling the parameterized constructor.
A a2(a1); // Calling the copy constructor.
cout<<a2.x;
return 0;
}
Test it Now
Output:

20

When Copy Constructor is called


Copy Constructor is called in the following scenarios:

o When we initialize the object with another existing object of the same class type. For
example, Student s1 = s2, where Student is the class.
o When the object of the same class type is passed by value as an argument.
o When the function returns the object of the same class type by valu

4. Constructor Overloading:-
 We can have more than one constructor in a class with same name, as long as
each has a different list of arguments.This concept is known as Constructor
Overloading and is quite similar to function overloading.
 constructor is called depending upon the number and type of arguments
passed.
 While creating the object, arguments must be passed to let compiler know,
which constructor needs to be called.
EX:-

// C++ program to illustrate


// Constructor overloading
#include <iostream>
using namespace std;
class construct
{
public:
float area;
// Constructor with no parameters
construct()
{
area = 0;
}
// Constructor with two parameters
construct(int a, int b)
{
area = a * b;
}

void disp()
{
cout<< area<< endl;
}
};
int main()
{
// Constructor Overloading
// with two different constructors
// of class name
construct o;
construct o2( 10, 20);

o.disp();
o2.disp();
return 1;
}

 Output:
 0
 200
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.
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
Output :-
{
cout<<"Constructor Invoked"<<endl; Constructor Invoked
}
~Employee() Destructor Invoked
{
cout<<"Destructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}

You might also like