0

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?

3
Contributors
3
Replies
4
Views
11 Years
Discussion Span
Last Post by dwks
0

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;
0

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;
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.