Dynamic Object Creation in C++
Dynamic Object Creation using new and delete in C++.
IntermediateMemory Management ProgramsExample 9 of 11
dynamic-object-creation.cpp
1#include <iostream>2#include <string>3using namespace std;45class Student {6private:7 string name;8 int age;9 int* marks;10 int numSubjects;1112public:13 Student(string n, int a, int nSub) {14 name = n;15 age = a;16 numSubjects = nSub;17 marks = new int[numSubjects]; // Dynamic array in object18 }1920 void setMarks() {21 cout << "Enter marks for " << numSubjects << " subjects: ";22 for (int i = 0; i < numSubjects; i++) {23 cin >> marks[i];24 }25 }2627 void display() {28 cout << "Name: " << name << endl;29 cout << "Age: " << age << endl;30 cout << "Marks: ";31 for (int i = 0; i < numSubjects; i++) {32 cout << marks[i] << " ";33 }34 cout << endl;35 }3637 ~Student() {38 delete[] marks; // Free dynamic array39 cout << "Destructor called for " << name << endl;40 }41};4243int main() {44 // Dynamically create object45 Student* student1 = new Student("Alice", 20, 3);46 student1->setMarks();4748 cout << "\nStudent 1:" << endl;49 student1->display();5051 // Create another object52 Student* student2 = new Student("Bob", 19, 3);53 student2->setMarks();5455 cout << "\nStudent 2:" << endl;56 student2->display();5758 // Free objects59 delete student1;60 delete student2;6162 cout << "\nObjects deleted" << endl;6364 return 0;65}
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
What's going on
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.