In C++, a constructor is a special type of method that is called automatically when an instance of the class (object) is created. The compiler calls the constructor and is used to initialize the data members of a newly created object.
The constructor has the same name as its class. Also, it doe not have any return type not even void.
Let us first look at the syntax of constructor in c++
1 2 3 4 5 6 7 8 9 10 11 | class A { public: int x; // constructor A() { // object initialization } }; |
Types of Constructor in C++
- Default constructor
- Parameterized constructor
C++ Default constructor
The constructor with no arguments is called a default constructor.
Let us look into the example of the C++ default Constructor.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | // C++ program for default constructor #include <iostream> using namespace std; // class class Square { private: float side; public: // constructor Square() { side = 12.4; cout << "Side: " << side << endl; } }; int main() { // creating an objects of Square class Square sq1; return 0; } |
Output:
Side: 12.4
Note: Default Constructor is used if the user does not define a constructor then the compiler creates a default constructor and initializes the member variables to its default values.
C++ Parameterized Constructor
A Constructor having a specific number of parameters is called Parameterized Constructor. Passing parameters is useful when you want to assign an initial value to an object at the time of its creation.
Let us look into the example of the C++ Parameterized Constructor.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | // C++ program for Parameterized constructor #include <iostream> using namespace std; // class class Rectangle { public: float length; float breadth; Rectangle(float l, float b) // constructor { length = l; breadth = b; } void CalArea() { float area = length * breadth; //display cout << "Area: " << area << endl; } }; int main() { // creating an objects of Rectangle class Rectangle rect1(6, 4); Rectangle rect2(3.5, 2.8); rect1.CalArea(); rect2.CalArea(); return 0; } |
Output:
Area: 24
Area: 9.8