Οι μέθοδοι αυτές μπορούν να χρησιμοποιηθούν για να διαχειριστούν τη
μνήμη αντικειμένων που απαιτούν τη χρήση δυναμικής μνήμης με κατάλληλες
κλήσεις στις new και delete.
Παράδειγμα:
#include <stdlib.h>
#include <iostream.h>
// Points in an N dimensional space
class pointnd {
private:
int *values;
int dimensions;
public:
pointnd(); // Default constructor
pointnd(int dimensions); // Constructor
pointnd(int dimensions, int value); // Constructor with initial value
~pointnd(); // Destructor
int &val(int dimension);
void display();
};
pointnd::pointnd()
{
pointnd::dimensions = 3;
values = new int[dimensions];
}
pointnd::pointnd(int dimensions = 3)
{
pointnd::dimensions = dimensions;
values = new int[dimensions];
}
pointnd::pointnd(int dimensions, int value)
{
pointnd::dimensions = dimensions;
values = new int[dimensions];
for (int i = 0; i < dimensions; i++)
values[i] = value;
}
pointnd::~pointnd()
{
delete[] values;
}
int &
pointnd::val(int dimension)
{
if (dimension > dimensions) {
cerr << "Point has only " << dimensions << " dimensions, not " << dimension << "\n";
exit(1);
}
return (values[dimension]);
}
void
pointnd::display()
{
for (int i = 0; i < dimensions; i++)
cout << values[i] << " ";
}
main()
{
pointnd a(3);
pointnd b(2, 0);
pointnd *c;
c = new pointnd[10];
a.val(0) = 8;
a.val(1) = 3;
a.val(2) = 4;
a.display();
cout << "\n";
b.display();
return (0);
}