Write a C++ program using constructor
#include <iostream>
using namespace std;
class Rectangle {
private:
int length;
int width;
public:
Rectangle(int l, int w) {
length = l;
width = w;
}
int getLength() {
return length;
}
int getWidth() {
return width;
}
};
int main() {
Rectangle rect(5, 10);
cout << "Length: " << rect.getLength() << endl;
cout << "Width: " << rect.getWidth() << endl;
return 0;
}
Explanation:
The program starts with the inclusion of the
iostream
library, which allows us to use input/output stream objects such ascout
.The
using namespace std;
line allows us to use the standard library functions and objects without having to prefix them withstd::
.We define a class called
Rectangle
to represent a rectangle. The class has two private member variables:length
andwidth
.Inside the class, we define a constructor for the
Rectangle
class. The constructor takes two integer parametersl
andw
, which represent the length and width of the rectangle, respectively. The constructor initializes thelength
andwidth
member variables with the values passed as arguments.We define two member functions
getLength()
andgetWidth()
inside theRectangle
class. These functions are used to retrieve the values of thelength
andwidth
member variables, respectively.In the
main()
function, we create an instance of theRectangle
class calledrect
and initialize it with the values 5 and 10.We use the
cout
object from theiostream
library to display the length and width of the rectangle using thegetLength()
andgetWidth()
member functions, respectively.Finally, we return 0 from the
main()
function to indicate successful program execution.