This slide will help you to learn dynamic memory allocation, new operator, delete operator, assigning value to pointer, pointer & constant, pointer and constant, constant pointer.
2. It means a program can obtain required
memory at runtime. Run time means when
the program starts executing not compile
time.
In C++ for dynamic memory allocation we
have two uninary operators.
◦ New
◦ Delete
3. It is used to allocate the memory space when
ever required.
It is also used to create objects of all types,
including a class name.
You can allocate memory to a pointer only at
runtime. Syntax is:
◦ Pointer-variable = new data-type
the data type may be a valid C++ data type
Pointer-variable is a pointer of type data-type
4. The type of allocating memory must be same to
the receiving pointer. it means, you can allocate
only integer type memory to an integer type
pointer.
Int *p = new int; Int *p = new char;
correct incorrect
5. To assign value to a pointer we have to pass a
value using “( )” .
Syntax will be:
◦ *p =100;
int *p =new int;
*p =200 int *p =new int(200);
6.
7. When an object, is not in use we must free the
memory captured by that object. So to free the
captured memory is done by “delete” operator.
The syntax is:
◦ Delete pointer-variable.
Int *p = new int;
----;
----;
delete *p;
8. We can use the keyword const for pointers
before the type, after the type, or in both
places. For example, all the following
declarations are legal:
◦ const int * p;
◦ int * const q;
◦ const int * const r;
Each of the above having different meaning
and different tasks.
9. *p is a pointer to a constant integer. The
value that is pointed to can‟t be changed.
We can say the int pointed to a constant.
10. „q‟ is a constant pointer to an integer. The
integer can be changed, but „q‟ can‟t point to
anything else.
„q‟ is constant, it can‟t point to anything else.
11. „r‟ is a constant pointer to a constant integer.
The value that is pointed to can‟t be changed,
and „r‟ can‟t be changed to point to anything
else.