Search code examples
c++oop

How to share the A::a value to the other class B::b, if in A class i have class B object


So, I'm creating the c++ project and I've encountered a new problem. And the question is: How i can get the A::a value in efficent way. I will mention that class A is pretty big and i dont want to get the A class obj. Here's the simplified version of the problem:

#include <iostream>
using namespace std;

class A
{
public:
    int a = 0;
    A(int n): b(5)
    {
        a = n; 
    }
private:
    B b;
};

class B
{
public:
    int b = 0;
    B(int n)
    {
        b = n;
    }
    void test()
    {
        // here how i can get the A::a value in most efficent way
    }
};

int main()
{
    A a(10);
    B b(20);
    b.test();
    return 0;
}

I was thinking about giving A::a ptr to the B class, but i find it pretty lame. I'm curious about your opinion.


Solution

  • Pass your A instance by reference to test:

    void test(A & obj)
    {
        // now you can access obj.a
    }
    

    If you need to access A::a just for reading (not modifying), it's better to pass by const reference so that the compiler will enforce that:

    void test(A const & obj)
    {
        // now you can access obj.a (for reading only)
    }
    

    Usage:

    A a(10);
    B b(20);
    b.test(a);
    

    Another alternative is to pass the instance by pointer / const pointer:

    void test(A * pObj)  {...} // now you can access pObj->a
    // or:
    void test(A const * pObj) {...} // now you can access pObj->a (for reading only)
    

    Usage:

    A a(10);
    B b(20);
    b.test(&a);  // note the `&` for taking the address of the object
    

    However, it is usually recommended in C++ to prefer references over pointer when applicable. See some more info here.

    A side note:
    it's better to avoid using namespace std; - see: What's the problem with "using namespace std;"?.