Dynamic Object Creation
Dynamic Object Creation using new and delete in C++
IntermediateTopic: Memory Management Programs
C++ Dynamic Object Creation Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int age;
int* marks;
int numSubjects;
public:
Student(string n, int a, int nSub) {
name = n;
age = a;
numSubjects = nSub;
marks = new int[numSubjects]; // Dynamic array in object
}
void setMarks() {
cout << "Enter marks for " << numSubjects << " subjects: ";
for (int i = 0; i < numSubjects; i++) {
cin >> marks[i];
}
}
void display() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Marks: ";
for (int i = 0; i < numSubjects; i++) {
cout << marks[i] << " ";
}
cout << endl;
}
~Student() {
delete[] marks; // Free dynamic array
cout << "Destructor called for " << name << endl;
}
};
int main() {
// Dynamically create object
Student* student1 = new Student("Alice", 20, 3);
student1->setMarks();
cout << "\nStudent 1:" << endl;
student1->display();
// Create another object
Student* student2 = new Student("Bob", 19, 3);
student2->setMarks();
cout << "\nStudent 2:" << endl;
student2->display();
// Free objects
delete student1;
delete student2;
cout << "\nObjects deleted" << endl;
return 0;
}Output
Enter marks for 3 subjects: 85 90 88 Student 1: Name: Alice Age: 20 Marks: 85 90 88 Enter marks for 3 subjects: 92 87 91 Student 2: Name: Bob Age: 19 Marks: 92 87 91 Destructor called for Alice Destructor called for Bob Objects deleted
Understanding Dynamic Object Creation
Dynamic object creation allows you to create objects at runtime using new. The object exists until explicitly deleted with delete. Dynamic objects are stored on the heap. When deleting, the destructor is automatically called. This is useful for: 1) Objects with unknown lifetime, 2) Large objects, 3) Polymorphism with base class pointers, 4) Collections of objects.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.