The simplest way is to allocate raw memory of the required length using a pointer-to-pointer to the class of object. Once you have the memory, you can access the individual elements just as you would any other type of array, to either instantiate new objects or to point to existing objects.
The following example uses the class itself to allocate a dynamic array of a given size, via a static member function.
// Declare a simple class with a default constructor,
// one member variable and a static member function.
class MyClass
{
public:
MyClass():m_int(0){} // Default constructor initialises member variable.
private:
int m_int; // Member variable.
public:
static MyClass CreateArray(unsigned int count); // Static member function.
};
// Implementation of the static member function.
MyClass MyClass::CreateArray(unsigned int count)
{
MyClass ppResult = NULL;
if( count )
{
// Calculate size of allocation.
size_t size = count * sizeof( MyClass* );
// Allocate memory and zero.
if( ppResult = ( MyClass ) malloc( size ))
memset( ppResult, 0x00, size );
}
return( ppResult );
}
int main()
{
// Some variables.
int i = 0;
MyClass** ppArray;
// Instantiate objects in a fixed-size array (uses default constructor).
MyClass Array[10];
// Instantiate a dynamic array of objects (and check for NULL).
if( ppArray = MyClass::CreateArray( 10 ))
{
// Point array elements to the existing objects.
for( i=0; i<10; ++i )
ppArray[i] = &Array[i]; // Any existing object will do here.
// ...do stuff...
// Finished with dynamic array (does NOT destroy the existing objects).
delete( ppArray );
ppArray = NULL;
}
// Instantiate a new dynamic array (and check for NULL).
if( ppArray = MyClass::CreateArray( 5 ))
// Instantiate new objects via default constructor.
for( i=0; i<5; ++i )
ppArray[i] = new MyClass();
// Note: it's worth checking each element is not NULL before accessing it!
// ...do stuff...
// Destroy each object that was created.
for( int i=0; i<5; ++i )
{
delete( ppArray[i] );
ppArray[i] = NULL;
}
// Finished with dynamic array.
delete( ppArray );
ppArray = NULL;
}
return( 0 );
// Array[10] will now fall from scope...
}
Copyright © 2026 eLLeNow.com All Rights Reserved.