๐๏ธ Object Lifecycle Management
Constructors initialize objects when created, while Destructors clean up resources (closing files, releasing Heap memory) when objects are destroyed.
๐ ๏ธ Key Concepts
๐ป Code Example: RAII Buffer Allocation Class
โC++ Source Code (main.cpp)
#include <iostream>
class DynamicBuffer {
private:
int *data;
int size;
public:
// Constructor with Member Initializer List
DynamicBuffer(int s) : size(s), data(new int[s]) {
std::cout << "๐๏ธ Allocated buffer of size " << size << " on Heap." << std::endl;
}
// Destructor (RAII Resource Cleanup)
~DynamicBuffer() {
delete[] data;
std::cout << "๐งน Destructor freed Heap memory buffer." << std::endl;
}
};
int main() {
{
DynamicBuffer buf(1024); // Object scope begins
} // Object goes out of scope here -> Destructor fires automatically!
return 0;
}
โWindows 11 Pro Terminal Execution OutputWindows 11 Pro Verified
โAdministrator: Windows 11 Pro Command Prompt (g++ GCC 13.2.0)
โโกโ
Microsoft Windows [Version 10.0.22631.3007] (Windows 11 Pro x86_64)
(c) Microsoft Corporation. All rights reserved.
C:\Users\Student\CPP_Project>#include <iostream>
C:\Users\Student\CPP_Project> g++ -o main.exe main.cpp
C:\Users\Student\CPP_Project> main.exe
Hello World from C++ on Windows 11 Pro!
[Process exited with code 0 in 0.001 seconds]