- 2072 Kartik · 6 marks
Dynamic memory for object and object array
Short answer
For a single object: Student *p = new Student(args); use p->method(); delete p. For array: Student *a = new Student[n]; calls default constructor n times; access a[i].method(); delete[] a. Must have default constructor for arrays. Use -> with pointer, . with array element.
With suitable example, explain dynamic memory allocation for object and object array.
Objects can be created on the heap with new and destroyed with delete. new allocates memory and calls the constructor; delete calls the destructor and then frees memory.
Single object
Student *p = new Student("Ram", 10); // calls constructor
p->display(); // access through pointer
delete p; // calls destructor, frees memory
Array of objects
Student *s = new Student[n]; // calls default constructor n times
s[i].display(); // or (s+i)->display()
delete[] s; // calls destructor for each element
The class must have a default constructor because no arguments can be passed in new T[n].
Example program
#include <iostream>
using namespace std;
class Student
{
int roll;
float marks;
public:
Student() { roll = 0; marks = 0; }
Student(int r, float m) { roll = r; marks = m; }
void read()
{
cout << "Enter roll and marks: ";
cin >> roll >> marks;
}
void display() { cout << roll << " " << marks << endl; }
~Student() { cout << "Object " << roll << " destroyed\n"; }
};
int main()
{
Student *p = new Student(1, 78.5); // one object
p->display();
delete p;
int n;
cout << "Number of students: ";
cin >> n;
Student *s = new Student[n]; // array of objects
for (int i = 0; i < n; i++)
s[i].read();
for (int i = 0; i < n; i++)
s[i].display();
delete[] s; // destructors called for all
return 0;
}
Points
- Use
->with a pointer to an object and.with an array element. - Use
delete[]for arrays; plaindeleteon an array gives undefined behaviour. - Dynamic objects live until deleted, so a memory leak occurs if we forget
delete.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Dynamic memory allocation with new and delete · Object Oriented Programming, chapter 3 · asked 2×
- File system vs virtual memory; contiguous allocation · Operating System, chapter 5
- Array representation vs dynamic list · Data Structure and Algorithm, chapter 3
- Array list; static or dynamic choice · Data Structure and Algorithm, chapter 3
- Static and dynamic data structures; array list · Data Structure and Algorithm, chapter 3