getArea() function

Hi! I have a class named Rectangle with the private members:
double width; double height;

I have a a get function which returns the area of the rectangle.

I have written:

double Rectangle::getArea()
{
double area = (width * height);
return area;
}

But I wonder. Should I use the getWidth(); and getHeight(); functions in the getArea(); function?

Is it better to write:
double Rectangle::Area()
{
double width = getWidth();
double height = getHeight();
double area = (width * height);
return area;
}

I guess that the first geArea() code won't know what the width and height is? How should I write the getArea() function?

I guess that the first geArea() code won't know what the width and height is?
A class function has access to all of it's object data.

Of the two functions, the first one is way better. There isn't much point in using get/set functions within the class (all that function call overhead).

I would reduce function one even further:
1
2
3
4
double Rectangle::getArea()
{
    return width * height;
}
Last edited on
thanks!

My set function setWidth(); is supposed to retun 0.0 if the width is negative. Is this code correct, or is it a better way to do it?
1
2
3
4
5
6
7
8
9
10
11
void Rectangle::setwidth(double width)
{
	if (this->width < 0)
	{ 
		this->width = 0.0; 
	}
	else
	{
		this->width = width;
	}

I think that what you are trying to do is check to see if the value of width which is being passed in through method setwidth is greater than 0. You should change your if statement to read:

 
if (width < 0) { ... }


The reason for this, is that when you are checking this->width, you are checking the value already stored in your class' member variable, called width. In this case, the this pointer is differentiating between that member variable and the parameter of the same name being passed in.

Another was of writing this which might be less confusing, or at least clarify what is happening here, would be like this:

1
2
3
4
5
6
7
8
void Rectange::setwidth(double w)
{
  if (w < 0) {
    width = 0.0;
  } else {
    width = w;
  }
}


~psault
I see! thanks! are there any rules for when I should use this->width, and when I can write width = integer; ?
Topic archived. No new replies allowed.