C++ Constructors
ποΈ C++ Constructors
A constructor in C++ is a special class method that is automatically called when an object is created.
Its main purpose is to initialize the data members of a class.
πΉ 1. Key Properties of Constructors
Name is same as class name
No return type (not even
void)Called automatically at object creation
Used to initialize objects
πΉ 2. Default Constructor
A constructor with no parameters.
πΉ 3. Parameterized Constructor
A constructor that accepts parameters.
πΉ 4. Constructor Overloading
Multiple constructors in the same class with different parameters.
πΉ 5. Default Values Using Constructors
πΉ 6. Copy Constructor
Used to create an object from another object.
Called when:
πΉ 7. Constructor with this Pointer
πΉ 8. Constructor Initialization List (Best Practice)
β Faster
β Required for const members
πΉ 9. Explicit Constructor
Prevents implicit conversions.
πΉ 10. When Constructor Is Not Written
The compiler provides a default constructor automatically if no constructor is defined.
β Common Mistakes
π Constructor vs Destructor
| Constructor | Destructor |
|---|---|
| Initializes object | Cleans resources |
| Called at creation | Called at destruction |
| Can be overloaded | Cannot be overloaded |
π Summary
Constructors initialize objects
Called automatically
Can be default, parameterized, copy
Support overloading
Initialization lists are recommended
