C++

Constructors and Destructors in C++

In Object-Oriented Programming, managing the lifecycle of an object—from the moment it is created in memory to the moment it is destroyed—is critical. C++ provides two special member functions for this purpose: Constructors and Destructors.

1. The Theory: Automatic Lifecycle Management

Theoretically, constructors and destructors ensure that an object is always in a "valid state."

  • The Constructor: Its job is Initialization. It sets the initial values of data members and acquires resources (like opening a file or allocating memory) the moment an object is born.

  • The Destructor: Its job is Cleanup. It ensures that when an object's lifetime ends, it releases any resources it held, preventing memory leaks or locked files.

Fundamental Rules:

  1. They have the same name as the class.

  2. They do not have a return type (not even void).

  3. They are called automatically by the compiler.

  4. Constructors can be overloaded; Destructors cannot.

2. Types of Constructors

A. Default Constructor

A constructor that takes no arguments. If you do not write any constructor, the C++ compiler generates a "compiler-defined default constructor" for you. However, it often leaves variables with garbage values.

B. Parameterized Constructor

A constructor that accepts arguments to initialize an object with specific values. This allows you to create different objects with different starting data.

C. Copy Constructor

A special constructor used to create a new object as a copy of an existing object.

  • Theory: It is essential when passing objects by value to functions. By default, C++ does a "shallow copy," but if your object uses dynamic memory (pointers), you must write your own Copy Constructor to perform a "deep copy."

3. Long Theory: The Destructor and Deterministic Destruction

The destructor is identified by the tilde symbol (~) followed by the class name (e.g., ~Student()).

A. When does it run?

The theory of Deterministic Destruction is what makes C++ unique compared to languages like Java or Python.

  • Local Objects: Destroyed as soon as the code execution leaves the block { } where they were defined.

  • Global Objects: Destroyed when the program terminates.

  • Dynamic Objects: Destroyed only when you explicitly call delete.

B. The "Resource Acquisition Is Initialization" (RAII) Principle

This is the most important theoretical concept in C++ resource management. RAII means that the holding of a resource is tied to the object's lifetime.

  1. The Constructor acquires the resource (memory, file, network socket).

  2. The Destructor automatically releases it.

    This ensures that even if an error occurs or the program exits early, the destructor will run and clean up the mess.

4. Practical Code Example

#include <iostream>
#include <string>
using namespace std;

class Wall {
private:
    double length;

public:
    // 1. Parameterized Constructor
    Wall(double len) {
        length = len;
        cout << "Constructor: Creating a wall of length " << length << endl;
    }

    // 2. Destructor
    ~Wall() {
        cout << "Destructor: Cleaning up wall resources." << endl;
    }

    double getLength() {
        return length;
    }
};

int main() {
    cout << "--- Main Starts ---" << endl;

    {
        // Creating an object inside a local scope
        Wall w1(10.5);
        cout << "Wall length: " << w1.getLength() << endl;
        
        // w1 will be destroyed here when the scope ends
    } 

    cout << "--- Main Ends ---" << endl;

    return 0;
}

5. Summary Table

FeatureConstructorDestructor
PurposeInitializes the object.Cleans up after the object.
SyntaxClassName()~ClassName()
Call TimingWhen object is created.When object goes out of scope.
ArgumentsCan take arguments (Overloading).Cannot take arguments.
Return TypeNone.None.
Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now