What is the error in this code?
I tried this code in Visual Studio, and I’m facing an error while running this code. Visual Studio is showing the error on line 29.
Point out the error and also explain it, please.
#include <iostream>
using namespace std;
class Rectangle {
int width;
int height;
public:
Rectangle(int w, int h) {
width = w;
height = h;
}
void setDimensions(int w, int h) {
width = w;
height = h;
}
int calculateArea() {
return width * height;
}
};
int main() {
Rectangle myRectangle(3, 4);
cout << "Initial Area: " << myRectangle.calculateArea() << endl;
myRectangle.width = 5;
cout << "Updated Area: " << myRectangle.calculateArea() << endl;
return 0;
}
3
Answers
.width is private member of class. It cannot be accesed from outside of the class. You should use setDimensions() to change it.
Since your class hasn’t any members that depend on width, nothing will break if you make it public.
If for example you wish to keep area as a class member to avoid calculating it every time the area is requested, then you must keep width private because any change of width will invalidate precalculated value of area. In this case keep it private and add special methods for class: one to get width wtithout right to change it and one that allows to set width and updates area with each change. (You only have second method in form of setDimensions())
On unrelated note:
The error in your code is on the line myRectangle.width = 5;. In the main function, you are trying to access the width member variable directly, but it is declared as private within the Rectangle class. Direct access to private members from outside the class is not allowed.
To fix this, you should use the public member function setDimensions to update the dimensions of the rectangle.
The error in the code is that the width and height member variables of the
Rectangle
class are private. Therefore, they cannot be accessed directly from outside the class.In the
main()
function, the linerectangle.width = 5;
tries to access thewidth
member variable of therectangle
object, which is not allowed and causes a compile-time error.To fix this error, you can add a public member function to the
Rectangle
class that allows you to set thewidth
andheight
member variables. For example, you can add the following function to theRectangle
class:Then, you can use this function to set the
width
andheight
of therectangle
object in themain()
function, like this:This will set the
width
of therectangle
object to5
and theheight
to6
, and the program will run without errors.