Constructor Overloading, Copy Constructor, Dynamic Constructors & Destructors
Idea in plain words
Constructor: Special member function sharing the class name, invoked automatically upon object instantiation to initialize state; has no return type.
Exam tip
High-yield exam topic (Very High).
Explanation
The constructor-destructor lifecycle forms the basis of RAII (Resource Acquisition Is Initialization), C++'s primary paradigm for resource safety. When classes manage heap buffers, file handles, or network sockets, adhering to the Rule of Three (Destructor, Copy Constructor, Copy Assignment Operator) prevents resource leaks and dangling pointers.
Key points
- Default Constructor (no arguments), Parameterized Constructor, Overloaded Constructors.
- Copy Constructor: ClassName(const ClassName &source). Called during initialization from another object, pass-by-value, and return-by-value.
- Shallow Copy vs Deep Copy: Shallow copy duplicates pointer addresses (causing double-free crashes upon destruction); Deep copy allocates new memory and duplicates pointed-to content.
- Destructor: ~ClassName(). Invoked automatically when an object leaves its scope; executes reverse cleanup (deletes heap memory allocated by dynamic constructors).
Example
Example
Order of destruction is strictly the reverse of construction order (LIFO - Stack order). Global objects are created before main() and destroyed after main() exits.
Code examples
// Deep Copy Constructor & Dynamic Constructor in C++
#include <iostream>
#include <cstring>
using namespace std;
class StringHolder {
private:
char *buffer;
public:
// Dynamic Constructor
StringHolder(const char *str = "") {
buffer = new char[strlen(str) + 1];
strcpy(buffer, str);
}
// Deep Copy Constructor
StringHolder(const StringHolder &other) {
buffer = new char[strlen(other.buffer) + 1];
strcpy(buffer, other.buffer); // Deep copy!
}
// Destructor
~StringHolder() {
delete[] buffer; // Safe memory cleanup
}
void display() const { cout << buffer << endl; }
};
Exam questions
- [8 Marks] What is a copy constructor? Explain shallow copy and deep copy with suitable diagrams and code snippets.
- [7 Marks] Explain dynamic constructors in C++ with an example of dynamic memory string handling.
- [7 Marks] Write a C++ program demonstrating the exact execution sequence of constructors and destructors in local and global scopes.