Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

OOP Part 2: Constructors and Destructors

Lesson 34 of 53 in the free Foundation of C & C++ notes on Siksha Sarovar, written by Rohit Jangra.

Automatic Setup and Cleanup

When you create a new object, you usually want to set its starting values immediately. C++ provides a special function called a Constructor to handle this automatically.

The Constructor

  1. It has the exact same name as the class.
  2. It has no return type (not even void).
  3. It is called automatically the millisecond the object is created.
class Player {
  public:
    int health;
    Player() { // Default Constructor
        health = 100;
    }
    Player(int h) { // Parameterized Constructor
        health = h;
    }
};

The Destructor

Just as objects are born, they eventually "die" (when they go out of scope). The Destructor is a special function called automatically to clean up.

  • Name: ~ClassName (Tilde followed by name).
  • Use Case: Freeing dynamic memory (delete), closing database connections, or saving a log file.

Constructor Overloading

You can have many constructors as long as they take different types of data. C++ will figure out which one to call based on the arguments you provide.

Initialization Lists (Pro Tip)

A faster, modern way to set values in a constructor:

Player(int h, int m) : health(h), mana(m) {} // Very efficient
If you don't write a constructor, C++ creates a invisible "Default" one for you. But as soon as you write any constructor, C++ stops providing the default one.