classes

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

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
// classes example
#include <iostream>
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
1
2
3
4
5
6
7
8
class CRectangle 
{
    // ...
   public: 
       // int area (void); // not const-correct.

       int area() const ;
};
:-D- 1 extra thought:

1
2
3
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.