Constructor In C++ | Constructor Explained With Real Life Example

 Constructor In C++ 



What is a constructor?

Constructor sounds like it will construct something, right? So yeah it is somewhat related to construction. So I will ask you a question if you want to stay in your house which is not built till now then what will you do? Maybe you will say what are you asking Dhruv. Well, the answer is very simple you will construct your house first. Am I right?. And you can do any change in your house during the construction right. So as in this example, the house will call class and the process of building your house will call the constructor. 

So when you create a class or call an object of any class then first before going into class first your class is calling constructor which will run by default but if you want to modify that constructor then you can do it.

Constructor is like a simple function that will run every time when we go inside a class.

Here is the official definition of a constructor - 

constructor is a member function of a class that initializes objects of a class. In C++, Constructor is automatically called when an object(instance of a class) create. It is a special member function of the class

Here are some rules to create a constructor -

 1. Special member function to do some tasks at first

 2.The moment you create an object constructor will automatically call

 3. Always define a constructor in public.

 4. Constructor name should be same as class name

5. Never use any return type. 

6. Can take an argument or not


Here You can see how a constructor is working - 

#include <iostream>
using namespace std;

class myClass
{
    public:
    //SIMPLE METHOD
    void get()
    {
        cout<<"I AM A METHOD"<<endl;
    }

    //CREATING CONTRUCTOR
    myClass()
    {
         cout<<"I AM A CONSTRUCTOR"<<endl;
    }
    
};


int main()
{

    myClass m1;//CREATING AN OBJECT
    m1.get();
    return 0;
}

Output - 

I AM A CONSTRUCTOR

I AM A METHOD


Whether We define the method at first but constructor will call automatically at first.

Comments

Popular posts from this blog

Array Of Objects In C++ | Array Of Objects Explained With Real Life Example

Pointers In C++ | Pointer Explained With Real Life Examples | Pointers In OOPs C++

Destructor In C++ | Destructor Explained With Real Life Examples