quick questions about classes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <cmath>
using namespace std;
class rectangle
{
    int x=5,y=4;
public:
    int surface (int x, int y) {return x*y;}
};


int main()
{
    int x=4, y=10;
    rectangle rect;
    cout << rect.surface(x,y);
}


why doesn't int surface (int x, int y) {return x*y;} conflict with private members x and y ? What does surface function return in this case? When is it determined what will function return: private class members or it's own members?
line 6 shouldn't even let you compile. Also the return type is int. You set that on line 8. As or the question about conflicting. Parameters take priority over private variables. If you have same name in the param list as your class variables you to access class variables you have to use the hidden "this" keyword. So to call x and y from your class it would be
1
2
this->x;
this->y;
If I'm not totally mistaken, you would have to use this.x in order to refer to the class variables.
This is a pointer so you would have to do this->x
True, true :)
Thank you giblit, one question, why line 6 wouldn't let me compile? I see nothing wrong with it
As far as I am aware you can only initialize static const variables inside of a class directly. To initialize the rest you would have to use a constructor or some sort of function in the class.

Like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Test
{
    int x , y;
    public:
        Test();
};
//initialized list
Test::Test() : x(5) , y(4){}
//without initialized list
Test::Test()
{
    x = 5;
    y = 4;
}



*edit
http://www.cplusplus.com/forum/general/87622/#msg470047
Last edited on
Even if you were referring to your class members, as opposed to the parameters, you'd still not be modifying them.
Topic archived. No new replies allowed.