In C++, you can access the values in two ways:
1. Encapsulation (or, by changing the protection level to the
public
, or protected in case of inheritance)
2. Creating a
friend
class
The first method is the easiest one, and I think is safer as well. You can simply change the access-level to the
public
or
protected
(if "class B" is a child of "class A"). Or, you can create getter/setter methods in the classes;
which you are already doing.
For the
friend
class, you can add a declaration suggesting that "class B" is a friend of "class A" and thus can access the fields. For more on the friend types in C++, please see
Friendship and inheritance - C++ Tutorials[
^] and
friend declaration - cppreference.com[
^].
What's going on in your code?
The problem with your code is that you are not reusing the same
A
object in your
B
class.
In you class B, you have this:
void getValue()
{
A obj;
int id = obj.getId();
std::cout << "Id : " << id << std::endl;
}
In the second line, you create a new instance of the A object. And you print the fresh value (which by default is zero in the constructor).
If you want to access the value of the A object, that you just set, try passing it to the method:
void getValue(A *obj)
{
int id = obj->getId();
std::cout << "Id : " << id << std::endl;
}
I have used the pointer to an A object, you can read more on this here:
Pointers - C++ Tutorials[
^].
Lastly, you need to pass the A object to this method and this should show the correct result for you.
I created a dummy program for you to test:
C++ Shell[
^]. It shows the output that you expect.