How we can access the private and protected members of class in other class or function without using inheritance. Write Example of Weight class which has two private data members kg and gram.There is a nonmember function AddTen() which object of weight class and adds the values ten to kg and gram.
It's possible to use friend function like this:
#include <iostream>
class Weight
{
private:
int kg;
int gram;
public:
Weight();
friend void AddTen(Weight& w);
};
Weight::Weight()
{
kg = 0;
gram = 0;
}
void AddTen(Weight& w)
{
w.kg += 10;
w.gram += 10;
}
int main(int argc, char* argv[])
{
Weight w;
AddTen(w);
return 0;
}
Comments
Leave a comment