+ 3

What is the difference between "Scope Resolution Operator" and "Friend function"?

I was told that both of them have the capability to access the data members of the class! Then what makes one, unique from that of the other?

21st Feb 2018, 4:06 PM
Shashank V Ray
Shashank V Ray - avatar
1 Réponse
+ 1
They are entirely different things. The scope resolution operator (::) helps access a function or variable from a specified scope. A scope, in general is an area or zone where a variable or function is accessible. The highest scope is the global scope, which allows variables to be accessed anywhere, and are followed by scopes local to functions, loops or classes. Eg : int x=2; // Global Scope x class m { public : static const int x = 3; }; // x local to the class m. int main() { cout<<x; //2 cout<<m::x; //3 if(x==2) { int x = 1;// Scope local to the if block. cout<<x; //1 cout<<::x; //2 } } Now, the :: operator, like in the above example helps access either the variable x inside the class or from the global scope. Similarly, it can be used for functions. A friend function is a special type of function that isn't a method (function belonging to the class, accessed by . ), but allows us to access private members of the class it is defined in inside it. Thus, even without being a member, a friend function can access all private variables. Eg : class Ex { int x=2; public : friend void print(Ex e) { cout<<e.x<<endl; } }; int main() { Ex a; print(a); //2. } As you can see from the above examples, friend functions and the scope resolution operator are unrelated and thus are non comparable.
21st Feb 2018, 5:09 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar