Non-member function cannot have access to private data of class - Functions

Q.  In any ways, Non-member function cannot have access to the private data of the class.
- Published on 19 Jul 15

a. True
b. False

ANSWER: False
 

    Discussion

  • Nihal   -Posted on 08 Oct 15
    If a function is defined as a friend function then, it can access the private and protected data of that class.
    To declare a friend function, declare its prototype within the class, preceding it with the keyword friend.
    Example:
    class Add {
    int a, b;
    public:
    friend int sum(Add x);
    void setValue(int i, int j)
    {
    a = i;
    b = j;
    }
    };
    // Note: sum() function is not a member function of any class.
    int sum(Add x)
    {
    /* Because sum() is a friend function of myclass, it can
    directly access private data a and b. */
    return x.a + x.b;
    }
    int main()
    {
    Add addObj;
    addObj.setValue(10, 20);
    cout <<"Summation =:"<< sum(addObj);
    return 0;
    }

Post your comment / Share knowledge


Enter the code shown above:

(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)