Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / C++ Programming Tutorial / Chapter 3: Object-Oriented Programming (OOP) in C++
CPP ⏱ 14 min read

Constructors and Destructors

Constructors guarantee an object is properly initialized the moment it is born; destructors guarantee resources are cleaned up when it dies.

What is it?

• Constructor: A special member method called automatically upon object creation, sharing the exact class name and having NO return type. • Destructor: Called automatically when an object goes out of scope, prefixed with a tilde `~ClassName()`.

Why is it used?

Implements RAII (Resource Acquisition Is Initialization)—C++'s core memory safety paradigm guaranteeing zero leaks.

Detailed Explanation

Types of Constructors: 1. Default Constructor: Takes no arguments. 2. Parameterized Constructor: Initializes attributes with provided values. 3. Member Initializer List (Best Practice!): `ClassName(int a) : var(a) {}` — initializes attributes directly before the constructor body executes, which is significantly faster for complex objects. 4. Destructor: Responsible for closing open file handles, releasing heap memory, and freeing network sockets.

Syntax Structure

Syntax Blueprint
class MyClass {
public:
    MyClass(int val) : data(val) {} // Constructor
    ~MyClass() {}                   // Destructor
};

Code Example

CPP Code
#include <iostream>
#include <string>

class CourseSession {
private:
    std::string course_title;
    int active_students;

public:
    // Parameterized Constructor using modern Member Initializer List
    CourseSession(const std::string &title, int students)
        : course_title(title), active_students(students) {
        std::cout << "[CONSTRUCTOR] Initialized session for: " << course_title 
                  << " with " << active_students << " students.\n";
    }

    // Destructor: Automatically cleans up when object leaves scope
    ~CourseSession() {
        std::cout << "[DESTRUCTOR] Closed session for: " << course_title 
                  << ". Resources released.\n";
    }

    void report() const {
        std::cout << "Session Active: " << course_title << "\n";
    }
};

int main() {
    std::cout << "=== Entering main() ===\n";
    
    // Block scope demonstration
    {
        CourseSession morning_batch("KLiC Advanced Python", 22);
        morning_batch.report();
        std::cout << "Exiting inner block scope...\n";
    } // morning_batch destructor is called immediately here!
    
    std::cout << "=== Ending main() ===\n";
    return 0;
}

Explanation of the Code

• Member initializer list `: course_title(title), active_students(students)` initializes variables directly. • When execution hits the closing curly brace `}`, the destructor runs automatically, guaranteeing memory safety.

Expected Output

=== Entering main() === [CONSTRUCTOR] Initialized session for: KLiC Advanced Python with 22 students. Session Active: KLiC Advanced Python Exiting inner block scope... [DESTRUCTOR] Closed session for: KLiC Advanced Python. Resources released. === Ending main() ===

Real-World Application

RAII powers smart pointers (`std::unique_ptr`), lock guards in multi-threaded servers, and database connection pools.

Common Mistakes to Avoid

• Allocating heap memory with `new` in a constructor without freeing it in the destructor (memory leak). • Putting a return type on a constructor or destructor (neither has a return type, not even `void`).

Quick Practice Challenge

Create a `DatabaseConnection` class with a constructor printing 'Connected' and a destructor printing 'Disconnected'.

Key Takeaways

• Constructors initialize objects; destructors clean up resources. • Always use member initializer lists for performance. • RAII ensures resources are released automatically when objects leave scope.