How to access a variable from another class: We can access the variable from another class by declaring the pointer variable of the class in the class where we want to access the variable. In the below example, we tried to access the data of val which is in the class two and we are trying to set and get the value for the variable val from the class one.
Below is the code in CPP:
Output:
given value is 30
Below is the code in CPP:
#include<iostream> using namespace std; class two{ public: two(){ val=0; } ~two(){ } void setVal(int x){ val = x; } int getVal(){ return val; } private: int val; }; class one{ public: two *b; one(){ a = 0; b =new two(); } ~one(){ } void setValue(int value) { b->setVal(value);// = value; } int getValue() { return b->getVal(); } private: int a; }; int main() { one obj; obj.setValue(30); cout<<"given value is "<<obj.getValue(); }
Output:
given value is 30
No comments:
Post a Comment