how can i use a class and dynamically allocate memory for an array?
my class is called Fraction.

int n;              /* n holds the user input */
    int *array;         /* array which you want to allocate later */
    
    cout << "Enter the number of array elements...";
    cin >> n;     /* get the user input */

    /* dynamically allocate the size of array to n times the length of an integer.*/    
    array = new int[n]; 


    /* some code...*/

    
    /* dont forget to delete the dynamically allocated array before quitting the program.. */    
    delete[](array);

is what you do for a regular dynamic allocation of memory in an array.
but how do i do it for a class?

Recommended Answers

All 3 Replies

you can allocate a class just like you did for that array

class MyClass
{
  // blabla
};

int n = 5;
// allocate an array of class objects
MyClass* pClass = new MyClass[n];
//
// allocate only one class object
MyClass* pClass = new MyClass;

You can delete it the same way, too.

class MyClass
{
  // blabla
};

int n = 5;
// allocate an array of class objects
MyClass* pClassA = new MyClass[n];
//
// allocate only one class object
MyClass* pClass = new MyClass;

// ...

delete [] pClassA;
delete pClass;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.