OOP Notes
Understand destructors and object cleanup — how C++ destructors work, Python
int main() { { FileLogger logger("app.log"); // Constructor called logger.log("Application started"); logger.log("Processing data"); logger.log("Data processed successfully"); } // logger goes out of scope — destructor called automatically!
std::cout << "After the block — file is safely closed" << std::endl; return 0; }
Logger opened: app.log Logger destroyed: app.log After the block — file is safely closed
class DatabaseConnection { private: Connection* conn;
public: DatabaseConnection(const std::string& connString) { conn = db_connect(connString); // Acquire resource if (!conn) throw std::runtime_error("Connection failed"); }
void query(const std::string& sql) { // Use the resource conn->execute(sql); }
~DatabaseConnection() { if (conn) { conn->close(); // Release resource delete conn; conn = nullptr; } } };
void processData() { DatabaseConnection db("host=localhost;db=myapp"); db.query("SELECT * FROM users"); // Even if query() throws an exception, // the destructor STILL runs and closes the connection! }
class ManagedResource: """Demonstrates both __del__ and the preferred context manager approach"""
def __init__(self, name): self.name = name self.data = [] print(f"Resource '{name}' acquired")
def __del__(self): """Called when garbage collected — but timing is unpredictable!""" print(f"Resource '{self.name}' released (via __del__)")
# Preferred: Context manager protocol def __enter__(self): return self
def __exit__(self, exc_type, exc_val, exc_tb): """Guaranteed cleanup when 'with' block ends""" self.cleanup() return False
def cleanup(self): self.data.clear() print(f"Resource '{self.name}' cleaned up properly")
with ManagedResource("database") as resource: resource.data.append("important stuff") # When this block ends, __exit__ is called — guaranteed!
Less reliable — __del__ may be called much later or never
resource = ManagedResource("temp") del resource # Suggests cleanup, but not guaranteed immediately
public class ConnectionPool implements AutoCloseable { private List<Connection> connections;
public ConnectionPool(int size) { connections = new ArrayList<>(); for (int i = 0; i < size; i++) { connections.add(createConnection()); } System.out.println("Pool created with " + size + " connections"); }
public Connection getConnection() { // Return an available connection return connections.stream() .filter(Connection::isAvailable) .findFirst() .orElseThrow(() -> new RuntimeException("No available connections")); }
@Override public void close() { // This is Java's version of a destructor for (Connection conn : connections) { conn.close(); } connections.clear(); System.out.println("Pool closed — all connections released"); } }
// Usage with try-with-resources (guaranteed cleanup) try (ConnectionPool pool = new ConnectionPool(10)) { Connection conn = pool.getConnection(); conn.query("SELECT * FROM users"); } // pool.close() called automatically here
| 1. **Name** | `~ClassName()` — tilde followed by class name |
| 2. **No parameters** | Destructors cannot take arguments |
| 3. **No return type** | Not even void |
| 4. **Only one per class** | You cannot overload destructors |
| 5. **Called automatically** | When object goes out of scope or `delete` is used |
| 6. **Virtual destructors** | Required in base classes used polymorphically |
// CRITICAL: Virtual destructors for polymorphism class Base { public: virtual ~Base() { // MUST be virtual! std::cout << "Base destroyed" << std::endl; } };
class Derived : public Base { int* data; public: Derived() { data = new int[100]; } ~Derived() override { delete[] data; // Without virtual base destructor, this NEVER runs! std::cout << "Derived destroyed" << std::endl; } };
Base* obj = new Derived(); delete obj; // Correctly calls ~Derived() then ~Base()
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Destructors in OOP.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Object Oriented Programming (OOP) topic.
Search Terms
object-oriented-programming, object oriented programming (oop), object, oriented, programming, oop, basics, destructor
Related Object Oriented Programming (OOP) Topics