

Cpp constructor code#
Let see the below code in which I am creating a parameterized constructor, one thing remember when creating the parametrized constructor then we have to pass the value at the time of creating the object. It is the reason we can create more than one constructor in the class that means constructor can be overloaded. We can pass the arguments in the constructor as per the requirement. Now I am calling the member function CalcuateArea to calculate the area and display the calculated area using another member function DisplayArea.Īrea(int l, int w):length(l),width(w),area(0) //constructor When the object “box” is created, the length and width of the object are initialized to 5 and 6 respectively. I have also defined two member functions CalculateArea and DisplayArea to calculate the area and to display the calculated area. In the below code, a constructor has defined which initializes length to 5 and width to 6. If required then we can also create own constructor and do some important task as per requirement. Whenever we create a new object then constructor invoked by the compiler to initialize the object. In the above example, I have created a constructor and initialize the integer variable with 0.

One point is important that constructor has a secret argument and this argument is “this pointer” (Address of the object for which it is being called). The name of the constructor must be the same as the name of the class and it does not return anything.īasically, a constructor is called by a compiler to initialize the class objects, so if you will not create own constructor then the compiler creates a default constructor. It is called by the compiler (automatically) whenever we create new objects of that class. Class constructors in C++ are special member functions of a class and it initializes the object of a class.
