Site icon i2tutorials

CPP – Member Dereferencing Operators

Member Dereferencing Operators

C++ allows you to define class members with pointers. To do so, C++ supplies a set of three pointer-to-member operators.

 

C++ Memory Management Operators

Need for Memory Management operators:

The term arrays have a dedicated memory block. The drawback of the array concept is that the programmer should know, during programming, the size of the memory to be allocated in addition to the size of the array remaining constant.

 

In programming, there may be scenarios where programmers may not know the memory needed until runtime. In this case, the programmer can choose to reserve as much memory as possible, assigning the maximum memory space needed to handle this situation. This would result in a waste of unused memory areas. Memory management operators are used to manage this situation within the C++ programming language.

 

C++ has two types of memory management operators: 

These two memory management operators are used for allocating and releasing memory blocks in an efficient and convenient way.

 

new operator: It is used for dynamic storage allowance. The new operator allows you to create objects of any type.

The general syntax of this new operator under C++ is:

pointer variable = new datatype;

 

delete operator: The C++ delete operator is used to release memory space when the object is no longer required. Once a new operator is used, it is effective to use the corresponding deletion operator to free up memory. 

The general syntax for the delete operator in C++ is:

delete pointer variable;

 

Example1:

#include <iostream>
using namespace std;
int main()
{
// Allocates memory space using new operator for storing a integer datatype
int *a= new int;
 *a=100;
cout << " The Output is:a= " << *a;
//Memory Released using delete operator
delete a;
return 0;
}

 

Output:

 

Example2:

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
 int num;
 cout << "Enter total number of students: ";
 cin >> num;
 float* ptr;
 // memory allocation of num number of floats
 ptr = new float[num];
 cout << "Enter GPA of students." << endl;
 for (int i = 0; i < num; ++i)
 {
 cout << "Student" << i + 1 << ": ";
 cin >> *(ptr + i);
 }
 cout << "\nDisplaying GPA of students." << endl;
 for (int i = 0; i < num; ++i) {
 cout << "Student" << i + 1 << " :" << *(ptr + i) << endl;
 }
 // ptr memory is released
 delete [] ptr;
 return 0;
}

 

Output:

 

Exit mobile version