A Constructor is a special member function that initializes a new object upon creation. A Destructor is invoked automatically when the object goes out of scope, releasing any allocated resources.
#include <iostream>
class DynamicArray {
private:
int* buffer;
int size;
public:
// 1. Parameterized Constructor with Member Initializer List
DynamicArray(int s) : size(s), buffer(new int[s]{}) {
std::cout << "Allocated array of size: " << size << "\n";
}
// 2. Deep Copy Constructor
DynamicArray(const DynamicArray& other) : size(other.size), buffer(new int[other.size]) {
for (int i = 0; i < size; ++i) {
buffer[i] = other.buffer[i];
}
std::cout << "Deep copy constructor executed!\n";
}
// 3. Destructor
~DynamicArray() {
delete[] buffer;
std::cout << "Destructor: Heap buffer released safely.\n";
}
};
int main() {
DynamicArray a1(5);
DynamicArray a2 = a1; // Calls Deep Copy Constructor!
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
High-speed resource transfer with rvalue references.
Why polymorphic base classes require virtual destructors.
Tying constructors and destructors to system resources.