CPP Tutorial



C++ CONSTRUCTORS


Constructors and Destructors in C++

In C++, constructors and destructors are special member functions of a class that are automatically called when an object is created or destroyed.

📌 Constructor: Initializes object data when the object is created.
📌 Destructor: Cleans up resources when the object goes out of scope or is deleted.

🔧 Constructor Characteristics:

  • Same name as the class.
  • No return type (not even void).
  • Can be overloaded (multiple constructors).

🔧 Destructor Characteristics:

  • Same name as the class, but with a ~ (tilde) before it.
  • No return type and no parameters.
  • Cannot be overloaded — only one destructor per class.

📄 Example: Constructor and Destructor

#include <iostream>
using namespace std;

class Student {
  public:
    Student() {
      cout << "Constructor called!" << endl;
    }

    ~Student() {
      cout << "Destructor called!" << endl;
    }
};

int main() {
  Student s1;
  return 0;
}
  

🖨️ Output:

Constructor called!
Destructor called!

🔍 Explanation:

  • When s1 is created, the constructor is automatically invoked.
  • At the end of main(), the destructor is automatically invoked.

🧠 Constructor Overloading

class Student {
  public:
    Student() {
      cout << "Default Constructor" << endl;
    }

    Student(string name) {
      cout << "Parameterized Constructor: " << name << endl;
    }
};

Student s1;            // Calls default constructor
Student s2("Rahul");   // Calls parameterized constructor
  

🎓 Summary

  • Constructor initializes objects when created.
  • Destructor cleans up memory or resources when objects are destroyed.
  • Both help in proper management of object lifecycle in C++.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review