Dynamic Allocation of Arrays And Objects

Arrays and objects can be allocated dynamically by using the new operator. To allocate a new array of five chars you can type for example:
char *pArray = new char[5];
To allocate an object of class ClassA:
ClassA *pObjectA = new ClassA;
In case a class has a constructor that takes parameters, such parameters have to be provided within parentheses:
ClassB *pObjectB = new ClassB(32);
Arrays of objects can be allocated.

Example


#include <iostream>
#include 
#include <string>
using namespace std;

class ClassA 
{
};

class ClassB 
{
    int b;

public:
    ClassB(int y) 
    {
        b = y;
    }
};

int main() 
{
    char *pArray;
    ClassA *pObjectA;
    ClassB *pObjectB;

    // Allocate an array
    try 
    {
        pArray = new char[5];
    }
    catch (bad_alloc except) 
    {
        cout << "pArray's new has failed" << endl;
        return 1;
    }
    
    // Allocate an array of objects
    try 
    {
        ClassB pArrClassB[3] = { {7}, {40}, {-100}};
    }
    catch (bad_alloc except) 
    {
        cout << "pArray's new has failed" << endl;
        return 1;
    }

    // Allocate a ClassA object
    try 
    {
        pObjectA = new ClassA;
    }
    catch (bad_alloc except) 
    {
        cout << "pObjectA's new has failed" << endl;
        return 1;
    }

    // Allocate a ClassB object
    try 
    {
        pObjectB = new ClassB(32);
    }
    catch (bad_alloc except) 
    {
        cout << "pObjectB's new has failed" << endl;
        return 1;
    }

    // Delete the array
    delete[] pArray;

    // Delete the two objects
    delete pObjectA;
    delete pObjectB;
}