In C++ a constructor is a special method of a class or structure in object-oriented programming that initializes a newly created object of that type. Whenever an object is created, the constructor is called automatically. Constructor is used to initializing objects of a class and allocate appropriate memory to objects. That is, it is used to initialize the instance variables of a class with a different set of values but it is not necessary to initialize.
Constructor Types:
- Default Constructor.
- Parameterized Constructor.
- Copy Constructor.
- Static Constructor.
- Private Constructor.
Example Of A Constructor:
#include <iostream>
#include <string>
using namespace std;
class Employee
{
public: //private: , protected:
string name;
int salary;
Employee(string n, int s, int sp)
{
this->name = n;
this->salary = s;
this->secretPassword = sp;
}
void printDetails()
{
cout<<"The name of our first employee is "<< this->name << " and his salary is " << this->salary<<" dollers"<<endl;
}
void getsecretPassword()
{
cout<<"The secret password is "<<this->secretPassword<<endl;
}
private:
int secretPassword;
};
class programmer : public Employee //inheritance
{
public:
int errors;
};
int main()
{
Employee ak("akshat constructor", 3000000, 23334);
ak.printDetails();
ak.getsecretPassword();
return 0;
}
There are no “return value” statements in the constructor, but the constructor returns the current class instance.