Consider the following C++ code. What will be printed when the program runs?
#include <iostream> using namespace std; class Box { public: Box() { cout << "Box created\n"; } ~Box() { cout << "Box destroyed\n"; } }; int main() { Box b; cout << "Inside main\n"; return 0; }
Think about when constructors and destructors are called in the program flow.
The constructor runs when the object b is created, printing "Box created". Then the program prints "Inside main". When main ends, the destructor runs, printing "Box destroyed".
Look at this code that uses a destructor to free memory. What is the output?
#include <iostream> using namespace std; class ArrayHolder { int* arr; public: ArrayHolder(int size) { arr = new int[size]; cout << "Array allocated\n"; } ~ArrayHolder() { delete[] arr; cout << "Array freed\n"; } }; int main() { ArrayHolder a(5); cout << "Working with array\n"; return 0; }
Remember the order of constructor and destructor calls for local objects.
The constructor allocates the array and prints "Array allocated". Then the program prints "Working with array". When main ends, the destructor frees the array and prints "Array freed".
Analyze this code. What will be printed when it runs?
#include <iostream> using namespace std; class Sample { public: Sample() { cout << "Sample created\n"; } ~Sample() { cout << "Sample destroyed\n"; } }; int main() { Sample* s = new Sample(); cout << "Pointer created\n"; delete s; cout << "Pointer deleted\n"; return 0; }
Think about when the destructor runs for objects created with new.
The constructor runs when new Sample() is called, printing "Sample created". Then "Pointer created" is printed. When delete s runs, the destructor prints "Sample destroyed". Finally, "Pointer deleted" is printed.
Consider this code where the destructor deletes a pointer that might be null. What happens when it runs?
#include <iostream> using namespace std; class Holder { int* ptr; public: Holder() : ptr(nullptr) { cout << "Holder created\n"; } ~Holder() { delete ptr; cout << "Holder destroyed\n"; } }; int main() { Holder h; cout << "Main ends\n"; return 0; }
Deleting a null pointer is safe in C++.
Deleting a null pointer does nothing and does not cause an error. So the destructor runs safely, printing "Holder destroyed" after "Main ends".
Choose the best description of what a destructor does in C++.
Think about what happens automatically when an object goes out of scope.
A destructor is a special function that runs automatically when an object is destroyed. Its main job is to free resources like memory or file handles and do cleanup tasks.