Constructors & Destructors
The lesson discusses in detail the use of constructors and destructors in classes, using some examples.
Introduction To Constructors
A class’s constructors control its initialization.
A constructor’s code executes to initialize an instance of the class when a program requests a new object of the class’s type.
Note: Constructors often set properties of their classes, but they are not restricted to doing so.
Constructor Declaration
Like other methods, a constructor can either have or not have parameters.
Note: A constructor’s name must be the same as the name of the class it is declared in.
It is also important to keep in mind that a constructor cannot return a value.
Note: No return type, not even
void
can be used while declaring a constructor.
Default Constructors
Constructors without any parameters are called default constructors.
The default constructor can be used to set some initial default value of the members of a class but it’s not necessary.
Example
Let’s take a look at how default constructors are declared and called.
Get hands-on with 1200+ tech skills courses.