Answer to Question #216954 in C++ for fiend

Question #216954
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-14T02:38:55-0400

Private and protected data members can be accessed using setters, getters and constructors. Constructors and setters are used to initialize the data members outside the class while getters are used to return the value of data members outside the classes.

#include<iostream>
using namespace std;
class Weight{
private:
int kg, gram;
public:
Weight(int k, int g){
kg = k;
gram = g;
}
int getKg(){
return kg;
}
int getGram(){
return gram;
}
};
void addTen(){
Weight t(10,20); //Example of how the kg and gram is initialized
cout<<"The original kg is:\t"<<t.getKg()<<"\tThe new kg is:\t"<<t.getKg() + 10<<endl;
cout<<"The original gram is:\t"<<t.getGram()<<"\tThe new gram is:\t"<<t.getGram()+ 10<<endl;
}
int main(){
addTen();
}

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