C++ Constructors and Destructors


What Is a Constructor?

In C++, a constructor is a unique method that triggers instantly upon the creation of an instance, initializing its internal structure.Its purpose is to prepare the object for use by assigning initial values to its data members. Constructors share their identifier with the class and execute without yielding any output type, including void.


Characteristics

  • Runs automatically when an object shows up.
  • Doesn’t require a return type.
  • Can be customized to accept values.
  • Allows overloading (you can define more than one version).

What Is a Destructor?

A destructor is another special member function that runs automatically when an object is about to disappear (goes out of scope or is deleted). Its job is to free up any memory or close resources (like files or connections) the object may have used.


Characteristics

  • Shares its name with the class but is preceded by a tilde (~).
  • No parameters and no return type allowed.
  • One per class; no overloading.

Example

#include 
using namespace std;

class Book {
public:
    string title;

    // Constructor
    Book() {
        title = "Untitled";
        cout << "Book object created." << endl;
    }

    // Destructor
    ~Book() {
        cout << "Book object destroyed." << endl;
    }

    void showTitle() {
        cout << "Title: " << title << endl;
    }
};

int main() {
    Book b1;  // Constructor runs here
    b1.showTitle();

    return 0; // Destructor runs automatically here
}
 

Explanation

  • When b1 is declared, the constructor activates and sets the default title to "Untitled".
  • showTitle() prints the value.
  • When main() ends, b1 is removed, and the destructor handles the cleanup.

Parameterized Constructor Example

class Car {
public:
    string model;

    Car(string m) {
        model = m;
        cout << model << " initialized." << endl;
    }
};

int main() {
    Car c1("Tesla");
    Car c2("Honda");

    return 0;
}
 
  • Car c1("Tesla"); triggers the constructor with "Tesla" as input.
  • Each object gets its own unique value at creation time.

Constructor Overloading (Multiple Constructors)

class Player {
public:
    string name;
    int score;

    // Default constructor
    Player() {
        name = "Unknown";
        score = 0;
    }

    // Constructor with one parameter
    Player(string n) {
        name = n;
        score = 0;
    }

    // Constructor with two parameters
    Player(string n, int s) {
        name = n;
        score = s;
    }

    void display() {
        cout << name << " scored " << score << " points." << endl;
    }
};

You can make multiple constructors, each tailored for a different initialization scenario.


Destructor Use Case Example

class FileHandler {
public:
    FileHandler() {
        cout << "File opened." << endl;
    }

    ~FileHandler() {
        cout << "File closed." << endl;
    }
};

int main() {
    FileHandler fh;  // Simulates opening a file
}
 

Here, the destructor would be a good place to release file access or clean up memory.


Summary

Constructors prepare objects for use, setting values or triggering setups the moment they’re created. Destructors clean up behind the scenes, ensuring that anything the object used is properly released before the object vanishes. These tools work automatically and silently, making sure your program runs smoothly without memory leaks or leftover resources. Together, they act like a welcome and exit handshake for every object in your C++ program.


Prefer Learning by Watching?

Watch these YouTube tutorials to understand C++ Tutorial visually:

What You'll Learn:
  • 📌 Constructor Basics | C++ Tutorial
  • 📌 Destructor Basics | C++ Tutorial
Previous Next