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?
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.
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)