๐งพ Unit 5: Constructor & Destructor [3 Hrs]
๐ โ๏ธ Theoretical Explanation
๐น Constructor
A constructor is a special member function that is automatically called when an object is created. It is used to initialize objects.
๐งฉ Characteristics of Constructors:
- Name must be the same as the class name.
- No return type (not even
void).
- Can be overloaded (multiple constructors with different parameters).
๐น Types of Constructors:
- Default Constructor โ
A default constructor is a constructor that takes no parameters. It is automatically invoked when an object is created. Useful for setting default values.
- Parameterized Constructor โ
A parameterized constructor allows values to be passed during object creation. This is useful to initialize an object with specific values.
- Copy Constructor โ
A copy constructor creates a new object by copying an existing one. It is useful when you want to make a clone of an object.
๐น Destructor
A destructor is a special member function that is automatically called when an object is destroyed. It is used to release resources. It's useful for releasing memory or closing files.
It deallocates all the memory previously used by the object of the class so that there will be no memory leaks.
๐งฉ Characteristics of Destructors:
- Same name as the class, preceded with a tilde
~.