You are using a version without Ads of this website. Please, consider donating:

### classes

hallo everyone, i am learning about c++ classes. the code below works but can you tell me why the sum result is wrong?

 ``1234567891011121314151617181920212223242526272829303132`` ``````// classes example #include using namespace std; class CRectangle { int x, y; public: void set_values (int,int); int area (void); }; void CRectangle::set_values (int a, int b) { x = a; y = b; } int CRectangle::area (void) { return (x+y); } int main () { CRectangle rect; int a,b,num; cout << "insert numbers a,b; "; cin >> a,b; rect.set_values (a,b); num = rect.area(); cout << "area: " << num << endl; system("Pause"); return 0; }``````

thx a lot
`cin >> a,b;` This doesn't do what you think.
You have to use operator>> twice.
`cin >> a >> b;`
Last edited on
Why is the area not `x*y` ?

Also the `(void)` are not necessary - just use () if there are no arguments for the function call.

It does no harm to leave them in, but they haven't been a requirement for a very long time.

HTH
 ``12345678`` ``````class CRectangle { // ... public: // int area (void); // not const-correct. int area() const ; };``````
:-D- 1 extra thought:

 ``123`` ``````double x; double y; double area() const ;``````
 cin >> a,b; This doesn't do what you think.

what does it do exactly?

 Why is the area not x*y ?

it was, changed thinking about some mathematical issue....felt lost :/

 class CRectangle { // ... public: // int area (void); // not const-correct. int area() const ; };

why specify type const for the variable area?

thx a lot to everybody

p.s. what should I do to insert the numbers like a,b or similar?
Last edited on
doraemon wrote:
why specify type const for the variable area?

You're promising that the function doesn't change any of the values within the class.

It's good practice. If you want to test it, try making your `set_values` function constant and see what happens.

doraemon wrote:
what should I do to insert the numbers like a,b or similar?

The way Peter87 detailed above.
Last edited on
 what does it do exactly?

The comma operator works by first evaluating the first operand, ignoring the return value, then it evaluates and returns the value of the second operand.
In your code `cin >> a` is the first operand and `b` is the second operand.
Last edited on
 You're promising that the function doesn't change any of the values within the class.

you mean that `int area() const ;` does not access to the class parameter ` int x, y; ` dontÂ´t you?
He means what he says. `int area() const` can still use `x` and `y` to calculate the area.
Topic archived. No new replies allowed.

You are using a version without Ads of this website. Please, consider donating: