Constructor In C++:

A constructor is a special type of member function of a class which initializes objects of a class. In C++, Constructor is automatically called when object(instance of class) create. It is special member function of the class because it does not have any return type.

Constructor Types:

  • Default Constructor.
  • Parameterized Constructor.
  • Copy Constructor.
  • Static Constructor.
  • Private 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;
    int secretPassword;
    class programmer : public Employee  //inheritance
        int errors;

int main()
    Employee ak("akshat constructor", 3000000, 23334);
    return 0;

Constructor is a special method that is used to initialize a newly created object and is called just after the memory is allocated for the object. It can be used to initialize the objects to desired values or default values at the time of object creation.

A constructor can be defined as a special member function which is used to initialize the objects of the class with initial values. It is special member function as its name is the same as the class name. It enables an object to initialize itself during its creation.

We use constructors to initialize the object with the default or initial state. The default values for primitives may not be what are you looking for. Another reason to use constructor is that it informs about dependencies.

Note that constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error. Synchronizing constructors doesn’t make sense, because only the thread that creates an object should have access to it while it is being constructed.

Leave a Reply

For News Subscribe Us!

Can curiosity may end shameless explained. True high on said mr on come. An do mr design at little myself wholly entire though. Attended of on stronger or mr pleasure.

You have been successfully Subscribed! Ops! Something went wrong, please try again.

© 2022 Code With AM