OOPS
Constructor and Destructor

Constructor

A constructor is a unique method that is automatically called during the creation of an object.
Its primary purpose is to initialize the data members of newly created objects. In C++, the constructor shares the same name as the class or structure it belongs to.

Types of Constructors:

  1. Default Constructor
    A constructor without any arguments is referred to as a default constructor.
    It is automatically called during the creation of an object.

  2. Parameterized Constructor
    A constructor with parameters is termed as a parameterized constructor.
    It is utilized to supply different values to individual objects.

  3. Copy Constructor (Important)
    A copy constructor is an overloaded constructor used to declare and initialize an object based on another object.
    It comes in two forms:

    • The default copy constructor provided by the language
    • The user-defined copy constructor

Learn More About Constructors (With Code Examples):


Destructor

A destructor in object-oriented programming (OOP) is a special member function of a class that is automatically called when an object is destroyed or goes out of scope.
Its primary purpose is to perform cleanup tasks, such as:

  • Releasing memory
  • Closing file handles
  • Disconnecting database connections

Learn More About Destructors (With Code Examples):


this Keyword / Pointer

The keyword this refers to the current instance of the class.
It serves three main purposes:

  1. It can pass the current object as a parameter to another method.
  2. It can refer to the current class instance variable.
  3. It can declare indexers.