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;
4
5class Student {
6private:
7 string name;
8 int age;
9 int* marks;
10 int numSubjects;
11
12public:
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 object
18 }
19
20 void setMarks() {
21 cout << "Enter marks for " << numSubjects << " subjects: ";
22 for (int i = 0; i < numSubjects; i++) {
23 cin >> marks[i];
24 }
25 }
26
27 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 }
36
37 ~Student() {
38 delete[] marks; // Free dynamic array
39 cout << "Destructor called for " << name << endl;
40 }
41};
42
43int main() {
44 // Dynamically create object
45 Student* student1 = new Student("Alice", 20, 3);
46 student1->setMarks();
47
48 cout << "\nStudent 1:" << endl;
49 student1->display();
50
51 // Create another object
52 Student* student2 = new Student("Bob", 19, 3);
53 student2->setMarks();
54
55 cout << "\nStudent 2:" << endl;
56 student2->display();
57
58 // Free objects
59 delete student1;
60 delete student2;
61
62 cout << "\nObjects deleted" << endl;
63
64 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.