C++ Concept Map

Dynamic Allocation

C++ allows the program to create and destroy objects at run-time, under program control. Two global operators, new and delete, make this happen.

The operator new takes a class name as argument, together with optional arguments that are passed to the appropriate class constructor, if available. It returns a pointer to the new object, which is created on the heap. A variable of type pointer-to-class can hold this returned value. For example:

class X { ... };

X* obj = new X;
In this case, the default constructor is called, since there are no arguments mentioned. However in:
class X {
...
public:
     X(int x);
...
};

X* obj = new X(32);
the constructor with a single integer parameter is used to initialize the new object.

Pointer variables follow the usual rules of scope, so it is possible for the variable to be deleted, leaving the object to which it points stranded (the "dangling pointer" problem). To avoid this, objects created with new should be deleted before this happens. For example:

class X { ... };

void f1() {
  X* x = new X;
  ...
  delete x;
}
Without the delete operation, the variable x would disappear, leaving the object to which it points without a pointer. Of course, pointers can be returned from functions, so they can be used with delete at a later time.

The operator delete calls the destructor function for the class of the argument.


Please mail any corrections and/or suggestions to Roger Hartley at
rth@cs.nmsu.edu

Copyright © 2003 Roger Hartley