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:
-
Default Constructor
A constructor without any arguments is referred to as a default constructor.
It is automatically called during the creation of an object. -
Parameterized Constructor
A constructor with parameters is termed as a parameterized constructor.
It is utilized to supply different values to individual objects. -
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:
- It can pass the current object as a parameter to another method.
- It can refer to the current class instance variable.
- It can declare indexers.