confused with classes

It's a simple program what calculates area from given numbers. I'm not sure why "&" in this part isn't necessary.
void get (int b, int c)
and
int calc_area(int, int)

If I put ampersand signs nothing changes. By my logic code without ampersand signs shouldn't work. Why is that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

class area
{
    int x=5, y=4;
public:
    int calc_area(int, int) {return x*y;};
    void get (int b, int c) {b=x; c=y;};
};
int main()
{
    area s;
    int a, b;
    s.get(a,b);
    int z= s.calc_area(a,b);
    cout << z;
}
You're confused.

The class Area (of a rectangle, it seems) should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Area
{
public:
    Area()
    {
        _x = 4;
        _y = 5;
    }

    int CalculateArea(int x, int y)
    {
        return x * y;
    }

    void Get(int x, int y) // Ampersands go here.
    {
        x = _x;
        y = _y;
    }

private:
    int _x;
    int _y;
};

See the commented line.
In your current code, a and b are useless; get does not initialize them, and calc_area does not use them.
Thanks, @Josue Molina, now I see - calc_area returns x * y , making a and b useless. My main idea was to get x and y values and then calculate area with them. I changed my code to this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

class area
{
    int x=5, y=4;
public:
    int calc_area(int i, int j ) {return i*j;};
    void get (int &b, int &c) {b=x; c=y;};
};
int main()
{
    area s;
    int a, b;
    s.get(a,b);
    int z= s.calc_area(a,b);
    cout << z;
}


I know it's messy but its the first time I'm learning classes. Are there any fatal mistakes there anymore?
Last edited on
┬┐why is `calc_area()' a member function if it does not use the state of the object?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

class area
{
    int x=5, y=4;
public:
    int calc_area() const {return x*y;}
    //void get (int &b, int &c) {b=x; c=y;}
};
int main()
{
    cout << area().calc_area() <<'\n';
}
also, all the objects would be equivalent
Last edited on
@ne555, I didn't want to make it simpler, I just wanted to test some things out. Anyways, why calc_area() returns zero in this code? When I call area s and use s instead of area() it seems to work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

class area
{
    int x, y;
public:
    int calc_area(){return y*x;};
    void get (int b, int c) {x=b; y=c;};
};
int main()
{
    int a, b;
    cin >> a;
    cin >> b;
    area().get(a,b);
    int z= area().calc_area();
    cout << z;
}
area() is a constructor, so you're creating a new instance of your area class for calculation rather than using an object.

1
2
3
area rectangle;
rectangle.get(a, b);
int z = rectangle.calc_area();
Topic archived. No new replies allowed.