In fact, it is not clear from your sample code what you are trying to achieve. :)
However, with regard to your code, the parameters of the functions are their local variables, which will end their lives after the functions are completed. Therefore, in this function
void set_a(int set) { a = &set; }
pointer a will contain the address of an object that no longer exists, which will lead to undefined program behavior. You must create a copy of a local variable in dynamic memory and assign the address of the copy to a member of class a . In this case, you should not forget to release the memory allocated dynamically.
The program may look like this.
#include <iostream> class A { protected: int *a = nullptr; public: ~A() { delete a; } void set_a(int set) { if ( a == nullptr ) a = new int; *a = set; } }; class B : public A { protected: int b; public: void show_b() { b = *(A::a); std::cout << b << std::endl; } }; int main() { B b; b.set_a( 10 ); b.show_b(); return 0; }
Or you can rewrite the program as follows.
#include <iostream> class A { protected: int *a = nullptr; public: ~A() { delete a; } void set_a(int set) { if ( a == nullptr ) a = new int; *a = set; } }; class B : public A { protected: int b; public: void show_b() { b = *(A::a); std::cout << b << std::endl; } }; int main() { B b; A &ra = b; ra.set_a( 10 ); b.show_b(); return 0; }
In this example, a reference to an object of class B declared, but of type A Using this link you can refer only to methods declared in class A
As for your question
how to pass the value obtained in one class to another.
this is done using class methods that return the resulting value. :)
For example,
#include <iostream> class A { private: int a; public: void set_a( int set ) { a = set; } int get_a() const { return a; } }; class B { private: int b; public: void show_b( const A &a ) { b = a.get_a(); std::cout << b << std::endl; } }; int main() { A a; a.set_a( 10 ); B b; b.show_b( a ); return 0; }