Question #216995

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.


Expert's answer

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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS