Answer to Question #216995 in C++ for fiend

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.


1
Expert's answer
2021-07-15T01:53:30-0400

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!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS