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();
}
Comments
Leave a comment