Tuesday, 21 May 2019

How to access private data in class? – tccicomputercoaching.com

The Friend function and friend class are the techniques used to access the private members of a class by using friend keyword.

A friend function is required when a function needs to access two or more independent classes, internal members.



For example,

#include <iostream.h>

class Distance
{
    private:
        int meter;
    public:
        Distance(): meter(0) { }
        //friend function
        friend int addFive(Distance);
};

// friend function definition
int addFive(Distance d)
{
    //accessing private data from non-member function
    d.meter += 5;
    return d.meter;
}

int main()
{
    Distance D;
    cout<<"Distance: "<< addFive(D);
    return 0;
}

Output

Distance: 5

To learn programming concepts in Best way, join TCCI in Satellite and Bopal-Ahmedabad.

Call us @ 9825618292

Visit us @ http://tccicomputercoaching.com/

No comments:

Post a Comment