Search code examples
c++methodsclass-design

How to call a method in one object from another object in the same structure


I have the following situation:

class B
{
    public:
        void methodInB();
};

class C
{
    public:
        void methodInC();
};

class A
{
    public: 
        void methodInA();
    private:
        B objB;
        C objC;
};

void A::methodInA()
{
    objB.methodInB();
}

int main()
{
    A objA;
    objA.methodInA();
    return 0;
}

I want to be able to call C::methodInC() from within B::methodInB(), but I'm not sure what the way to go about it would be (not without messing with globals).

My first idea was to add a C* pC pointer as a member of B, and then from methodInB() call it as pC->methodInC. This would require I set the pointer from within A before using the method (possibly in A's constructor). My problem is I may need to call other objects from within B if I add a D and E objects, and I don't want to fill the class definition with pointers.

Is there some other way of doing this? An implicit reference to the object the object belongs to? Kind of like this but for the parent? So I could at least do parent->objC->methodInC()?


Solution

  • I think the cleanest way would be to "inject the dependency", that is, to pass objC to methodInB, which would then invoke methodInC on that object:

    void A::methodInA()
    {
        objB.methodInB(objC);
    }
    
    // ...
    
    void B::methodInB(C &objC)
    {
        objC.methodInC();
    }