How To Create Constructor In C++:

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.

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