Trying to build overloading class, function returns a funny number
Jul 10, 2018 at 7:33pm UTC
Hi Im trying to build my 1st class to do some overloading but before i got to that part my box get its area function is returning a funny overflow number instead of 50. Why?
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 38 39 40 41
#include<iostream>
using namespace std;
class Box
{
public :
int SetitsHeight(int height) {height = itsHeight;}
int SetitsLength(int length){length= itsLength;}
int SetitsWidth(int width){width = itsWidth;}
int GetitsHeight(){return itsHeight;}
int GetitsLength(){return itsLength;}
int GetitsWidth(){return itsWidth;}
int GetitsArea(){return itsArea;}
Box operator +(Box & spare)
{
Box box;
box.itsWidth = this ->itsWidth + spare.itsWidth;
box.itsLength = this ->itsLength + spare.itsLength;
box.itsHeight = this ->itsHeight + spare.itsWidth;
box.itsArea = this ->itsArea + spare.itsArea;
return box;
}
private :
int itsWidth;
int itsLength;
int itsHeight;
int itsArea = itsWidth*itsLength*itsHeight;
};
int main()
{
Box Box1;
Box1.SetitsHeight(5);
Box1.SetitsWidth(5);
Box1.SetitsLength(5);
cout << "Box1s area is " << Box1.GetitsArea()<< endl;
}
Jul 10, 2018 at 7:57pm UTC
1 2 3 4
int itsWidth;
int itsLength;
int itsHeight;
int itsArea = itsWidth*itsLength*itsHeight;
That isn't how variables work. You can't assign
itsArea before itsWidth, itsLength, and itsHeight have valid values.
If you want itsArea to be a calculation dependent on itsWidth, itsLength, and itsHeight, turn it into a function instead:
int GetitsArea() { return itsWidth * itsLength * itsHeight };
box.itsHeight = this ->itsHeight + spare.itsWidth;
Copy-paste typo? Did you mean to do spare.itsHeight here?
PS: Very odd style to prepend everything with "its". Kinda needless verbosity, in my humble opinion.
Last edited on Jul 10, 2018 at 8:01pm UTC
Topic archived. No new replies allowed.