In C++, constructors and destructors are special member functions of a class that are automatically called when an object is created or destroyed.
~
(tilde) before it.#include <iostream> using namespace std; class Student { public: Student() { cout << "Constructor called!" << endl; } ~Student() { cout << "Destructor called!" << endl; } }; int main() { Student s1; return 0; }
s1
is created, the constructor is automatically invoked.main()
, the destructor is automatically invoked.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
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!