we are learning about classes in my c++ class and we are currently assigned to work on a class that will basically output the area of two rectangles. We are required to set the initial height and width both to 0.0. Also, we must set height = h and width = w. I think the code will speak for itself:
Ignore the commented code....That is something I am working on adding on to it. The end result is that we are supposed to compare two rectangles through an overloaded "==" function and output if they are equal or not. However, before I add the extras, there seems to be a problem with initialization somewhere involving the height and width. The program compiles but the area comes out to a strange exponential number. thanx.
now in your main, whichever constructor was called, area will be defined. Before area was only defined when getarea was called (and you never called it).
yes i understand now thank you. now the only problem is that i enter two numbers....for the first object in the main.....and the area outputs zero all the time. the second object (r2(5.00, 5.00)) calculates perfectly but r1 outputs zero. I am guessing that it is because of setting area to zero in the constructor?
actually I would recommend you remove area completely as member variable and always calculate it "on the fly" in getarea.
Then you don't print out r.area in your cout<< statement, but call to r.getarea(). Sounds better to me.
1 2 3 4 5 6 7 8 9 10 11
...
class rectangle
{
float height;
float width;
//float area; <-- don't store it as class variable
...
float getarea() const { return height*width; }
};
...
os << "The area is: " << r.getarea() << endl;
I agree with imi. More importantly though make sure you do remove area from the constructor. The constructor is not there to perform calculations, it is there to initialize your object.