CPP facilitates a special type of method, also called as CPP Constructors, to initialize the instance members of the class and to verify enough object resources for executing any startup task. It has the same name as the name of the class.
Types of Constructors:
Default Constructor:
A Default Constructor is automatically created at the time of creating object, without any arguments and parameters.
Parameterized Constructor:
A Parameterized Constructor is a constructor with parameters created in order to assign values to the objects.
Example 1: Example of Default Constructor
#include <iostream.h> using namespace std; class Employees { public: Employees() { cout << "Hello Employee!!" << endl; } }; int main() { Employees e1; Employees e2; return 0; } |
Output
Hello Employee!! Hello Employee!! |
Example 2: Example of Parameterized Constructor
#include <iostream.h> using namespace std; class Employees { public: string Name; float Salary; Employees(string n, float s) { Name = n; Salary = s; } void details() { cout << "Employee Name : " << Name << endl; cout << "Employee Salary: " << Salary << "\n\n"; } }; int main() { Employees e1 = Employees("Khush", 10000); Employees e2 = Employees("Raam", 20000); e1.details(); e2.details(); return 0; } |
Output
Employee Name : Khush Employee Salary: 10000 Employee Name : Raam Employee Salary: 20000 |