Unit-3 c++
Unit-3 c++
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
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;
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.
int i = 17;
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.
#include <iostream>
using namespace std;
int main()
{
int a = 10;
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 main()
{
// Allocating memory
int* ptr = new int(5);
// Deallocating memory
delete ptr;
return 0;
}
Output
ptr is now a dangling pointer
// 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;
}
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++.
int main() {
return 0;
}
Output
Value: 10
}
};
// 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
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
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;
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
#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
int main()
{
student s;
/*
constructor gets called automatically
as soon as the object of the class is declared
*/
s.display();
return 0;
}
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
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:-
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;
}