pass an object to a member function

Sep 13, 2015 at 11:03pm
I just don't understand why "s.total_val" works here. By doing the command "s1.topval(s2)"; topval(...) is a member function for object s1 therefore it can access the private data total_val of s1. However, s2 is another object and we should not be able to do something like s2.total_val inside the topval;(...). I think s2.gettotal() should work instead of s2.total_val. Could anyone help me on explaining why it works? When we pass an object to a member function as an argument, can we always explicitly access its private data?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class stock
{
private:
    double total_val;
public:
    stock(double m){ total_val = m;}
    double gettotal() const {return total_val;}
    stock& topval(stock& s);

};

stock& stock::topval(stock& s){
    if(s.total_val > total_val)
    {return s;}
    else
    {return *this;}
}
int main () {
    stock s1(1);
    stock s2(2);
    s1.topval(s2);
    return 0;
}
Sep 13, 2015 at 11:21pm
Does a member function belong to a class and can access the private data of all objects from the same class?
Sep 14, 2015 at 12:16am
Yes a member function can access all data inside the scope of the class. However, accessing the data through an object limits access to public UNLESS otherwise specified. I.E. friends or inheritance. Also you should know that if you declare any of your functions static they cannot access non-static data. A static member function is a class function, not a an object method meaning it can be called without the use of an object.
Sep 14, 2015 at 8:24am
When we pass an object to a member function as an argument, can we always explicitly access its private data?
Yes. All member functions can always access all other members. It does not matter if it is same object or other (Deep inside member functions are normal functions which are passed a pointer to object as first argument)
Sep 24, 2015 at 2:57am
Thank you so much Renthalkx97 and MiiNiPaa!
Topic archived. No new replies allowed.