-1

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()?

Kian
  • 1,654
  • 1
  • 14
  • 22
  • Your `objB` and `objC` don't know of each other. There's no such thing as generically "knowing who you belong to". If you want you can construct `objB` and `objC` with `A`'s `this` pointer, but you will have to tell them explicitly that they are contained, or where to find the sibling. – Kerrek SB Jun 22 '11 at 20:31
  • Didn't think there was. Still, that's why I'm asking. I know siblings don't know about each other, so how do I call one from the other? – Kian Jun 22 '11 at 20:43
  • You could construct each with a reference to the other, or both with a reference to the parent. Alternatively you redesign and make `A` *inherit* from `B` and `C`. – Kerrek SB Jun 22 '11 at 20:44
  • This has the potential to make the classes very dependent on each other, to the point that changing one would require changing a lot of others. In technical terms, this leads to high coupling. – David Thornley Jun 22 '11 at 20:57

2 Answers2

4

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();
}
Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
2

Let every class B, C, D, E, etc. have a pointer to the A object of which they are subobjects.

class A;
class C;
class B
{
    A* pA;
    void MethodB();
};


...

void B::MethodB
{
   (pa->CObject).MethodC();
}    
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434