-2

I'm struggling in finding out how to call a class B object in class A object.

#include <iostream>
using namespace std;

class A
{
public :
    void FA("an object param (aop)")
    {
        "aop".varB-=varA;
    }
protected :
    int varA = 1;
};

class B
{
public :
    int varB = 2;
};

int main()
{
    A a1;
    B b1;

    a1.FA("b1 object"); // I WANT TO CHANGE B1 MEMBER VALUE BY USING A1 FA FUNCTION

    cout << b1.varB;


    //Output: 1

    return 0;
}
François Andrieux
  • 28,148
  • 6
  • 56
  • 87
Saud
  • 13
  • 4
  • 2
    You probably want to use a forward declaration of class B and pass by reference in FA. like this `void FA( B & myB)`. The forward declaration is just `class B;` put that just before `class A` – drescherjm Oct 23 '18 at 13:31
  • 3
    C++ can't be learned by guessing. Please consider reading one of these [C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Ron Oct 23 '18 at 13:33

1 Answers1

1

Below is how I would do it. Note that this works because the dependency is one-way, i.e. A::FA() needs to know about the implementation details of B, but B doesn't need to know about the implementation details of A. If it ever became two-way (i.e. if you later added a method in B that needed to call methods on an A or access member variables of an A), then you'd need to use a forward declaration and move the B-class's method's implementation to a non-inline location after both class's declarations.

#include <iostream>
using namespace std;

class B
{
public:
    int varB = 2;
};

class A
{
public:
    void FA(B & b)
    {
        b.varB -= varA;
    }
protected:
    int varA = 1;
};

int main()
{
    A a1;
    B b1;

    a1.FA(b1);
    cout << b1.varB;

    //Output: 1

    return 0;
}
Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234