22 Jan C++ Constructors
A Constructor in C++ is always public and has the same name as the class name. Constructor gets called automatically when we create an object of a class. It does not have a return value. In this lesson, we will learn what are Constructors with examples and how to set parameters.
How to create a Constructor
In C++, to create a Constructor, the same class name is used followed by parentheses. Let’s say the class name is Studyopedia, therefore the Constructor would be the following:
1 2 3 4 5 |
Studyopedia() { // Constructor // Code comes here } |
Let us see an example to create a Constructor in C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> using namespace std; class Rectangle { public: // Access specifier // Constructor name is the same as the class name Rectangle() { cout << "Our Constructor!!"; cout << "\nA rectangle has 4 sides, 4 corners, and 4 right angles"; } }; int main() { /* Constructor gets called automatically when we create an object of a class */ Rectangle rct; return 0; } |
Output
1 2 3 4 |
Our Constructor!! A rectangle has 4 sides, 4 corners and 4 right angles |
Constructor Parameters
Parameterized Constructor is a constructor with a particular number of parameters. This is useful if you have different objects and you want to provide different values.
First, let us see what a parameterized constructor looks like with 2 parameters:
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 37 |
#include <iostream> using namespace std; class Rectangle { public: // Access specifier double length; double width; // Constructor name is the same as the class name Rectangle(double len, double wid) { length = len; width = wid; } }; int main() { /* Constructor gets called automatically when we create an object of a class */ Rectangle rct1(5, 10); Rectangle rct2(8, 20); Rectangle rct3(10, 25); // Display cout<<"Area of Rectangle1\n"; cout <<"Length = "<<rct1.length << ", Width = " << rct1.width <<"\n"; cout<<"\nArea of Rectangle2\n"; cout <<"Length = "<<rct2.length << ", Width = " << rct2.width <<"\n"; cout<<"\nArea of Rectangle3\n"; cout <<"Length = "<<rct3.length << ", Width = " << rct3.width <<"\n"; return 0; } |
Output
1 2 3 4 5 6 7 8 9 10 |
Area of Rectangle1 Length = 5, Width = 10 Area of Rectangle2 Length = 8, Width = 20 Area of Rectangle3 Length = 10, Width = 25 |
Now, let us understand the flow of parameterized constructors in the above program.
In the above code, we created 3 objects of the Rectangle class. As the parameters, we passed the length and width of the Rectangle to the parameterized constructor:
1 2 3 4 5 |
Rectangle rct1 = new Rectangle(5, 10); Rectangle rct2 = new Rectangle(8, 20); Rectangle rct3 = new Rectangle(10, 25); |
The length and width values pass to the parameterized constructor:
1 2 3 4 5 6 7 |
// parameterized constructor Rectangle (double len, double wid) { length = len; width = wid; } |
No Comments