Page 55 - DCAP404 _Object Oriented Programming
P. 55
Object-oriented Programming
Notes For example,
delete p;
delete q;
If we want to free a dynamically allocated array we must use the following form of delete.
delete [size]pointer_variable;
For example, statement
delete [ ]p;
will delete entire array pointed by p.
The new operator has several advantages over the function malloc().
1. It automatically computes the size of the data objects.
2. It automatically returns the correct pointer type so there is no need to use a type cast.
3. It is possible to initialize the object while creating the memory space.
4. They both it new and delete can be overloaded.
Did u know? What is the need for Memory Management operators?
The concept of arrays has a block of memory reserved. The disadvantage with the concept
of arrays is that the programmer must know, while programming, the size of memory to
be allocated in addition to the array size remaining constant.
In programming there may be scenarios where programmers may not know the memory
needed until run time. In this case, the programmer can opt to reserve as much memory as
possible, assigning the maximum memory space needed to tackle this situation. This
would result in wastage of unused memory spaces. Memory management operators are
used to handle this situation in C++ programming language.
2.6.2 Declaration of Variables
If you are familiar with C, you would know that, in C, all variables must be declared before they
are used in executable statements. This is true with C++ as well. However, there is a significant
difference between C and C++ with regard to the place of their declaration in the program.
C requires all the variables to be defined at the beginning of a scope. When we read a C
program, we usually come across a group of variable declarations at the beginning of each scope
level. Their actual use appears elsewhere in the scope, sometimes far away from the place of
declaration.
Before using a variable, we should go back to the beginning of the program to see whether it has
been declared and, if so, of what type it is. C++ allows the declaration of a variable anywhere in
the scope. This means that a variable can be declared right at the place of its first use. This makes
programs much easier to write and reduces the errors that may be caused by having to scan back
and forth. It also makes the program easier to understand because the variables are declared in
the context of their use. The following example illustrates this point.
main ( )
{
float x; // declaration
48 LOVELY PROFESSIONAL UNIVERSITY