0

I have a class "c" which has instances of classes "a" and "b" as its properties. I want to access methods of object A in object B. Currently, I defined a method in class b that wraps the "add" method of class a and added class a as a property of class b. Is there a better OOP way of accessing class a's methods in class b.

#include <iostream>

class a
{
public:
    a(){i = 1; j = 2;}
    int add() { return i + j; }

private:
    int i;
    int j;
};

class b
{
public:
    b() {}
    int add() { return k + l; }
    int adda() { return A.add(); }

private:
    int k;
    int l;
    a A;
};

class c
{
public:
    int add() { return A.add() + B.add(); }
    int addainb() { return B.adda(); }

private:
    a A;
    b B;
};

int main()
{
    c C;
    int res = C.addainb();
    std::cout << res << std::endl;
    return 0;
}
sujoybyte
  • 584
  • 4
  • 19
A.Agan
  • 103
  • 6
  • You should look into forward declaration: https://stackoverflow.com/questions/9119236/c-class-forward-declaration and more generally https://stackoverflow.com/questions/4757565/what-are-forward-declarations-in-c – Cosemuckel Apr 17 '23 at 18:33
  • 4
    The "better OOP way" would be to *not need* to access a "sibling" object from a given object. If `B` needs an `A`, it should contain (a reference to) an `A`. This is a problem of design. Produce a good design before you try to figure out how to implement it. – HTNW Apr 17 '23 at 18:43
  • How about defining the add function of class a as a friend function of class b? The same way mentioned here: https://www.geeksforgeeks.org/friend-class-function-cpp/ – A.Agan Apr 28 '23 at 14:42

1 Answers1

1

There are two ways I can see of doing this, firstly, define class B with a field that is a pointer (or reference) to a object of class A, and a constructor argument which is the A object you wish to reference you wish to reference/point to, and then in the C constructor create a class A object in the class before creating the class B object, and then pass the A object to the B object constructor, or you could use the functional standard library and pass wrapper functions to the B class (wrap calls to the A class methods into functions that capture this). Basically both options boil down to: (I’m going to use A to represent a instance of class A)

C creates A

C creates B, passing to the constructor A*

B calls A through the pointer it is passed

Pointers are quite useful, please do tell if you have anymore questions (or I misunderstood the question!)

wizard7377
  • 11
  • 3
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 20 '23 at 22:24