C++ Constructor
A constructor is a special member method or function for automatic initialization of an object.
A constructor executed automatically whenever an object is created. And you have to provide the constructor name as same as the class name. It is a kind of member function and initializes an instance of the class. It has the same name as the class name and no return value.
The constructor can have any number of the parameters of the class may have a number of constructors overloaded.
Rules for Constructor:-
- The constructor name must be the same as the class name.
- It has no return type.

Syntax:
class class_name { : data_type member_data; member functions(); class_name() // constructor { ......... } };
Types of Constructor
- Default constructor
- Parameterized constructor
Default Constructor
A Constructor having no arguments is known as the Default constructor. The default constructor is invoked at the time of the creation.
Example:
#include <iostream> using namespace std; class Rectangle{ public: int length=5,breadth=7; float area; Rectangle() //constructor { cout << "Enter the length and breadth value: " ; cin >> length >> breadth; cout << "Area of the Rectangle: "; area= length * breadth; cout << area; } }; int main(){ Rectangle r1; return 0; }
Parameterized Constructor
Constructor having the parameters(arguments) is known as the Parameterized constructor. Parameterized constructor is used to provide different values to the various objects.
Example:
#include <iostream> using namespace std; class Rectangle{ public: int length,breadth; float area; Rectangle(int length, int breadth) //Parameterized constructor { cout << "Area of the Rectangle: "; area= length * breadth; cout << area; } }; int main(){ Rectangle r1(4,5); return 0; }
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.