How to access parent object's parent from an object efficiently?

69 Views Asked by At

Sorry for the badly defined title. What I mean:

(Btw I am working on a game engine, and A is the Scene, B are the Game Objects and C are the Components)

I have 3 classes: A, B, C

  • A contains B, and B contains C.
  • A and B has a reference to each other.
  • B and C has a reference to each other.

(A is forward declarated in B's header, and included in B's implementation)

It's like this: A <-> B <-> C

My situation is this:

  • I want to use A's method from C. (Like telling the main container to add another B, etc)

  • ~I want to make a reusable function which calls a method at the parent object's parent.

  • For example in C's derived classes I don't have to care how C reaches A, I just call C's Reach-A-and-do-something method.

My question is that which one should I use and why (or is there a better one?):

  • In C: GetB().GetA().DoSomething()

  • C's DoSomething() calls B's DoSomething() which calls A's DoSomething.

The first one looks nicer to me, but in C's implementation i only include B's header, where A is only forward declarated. So I can't use A's methods without explicitly including it in C. (Is this a bad practice, or should I just include it?)

The second one has a big overhead. If I want to use A's XY method, I have to create an XY method in B which calls A's XY and I have to create an XY method in C which calls B's XY.

So I don't know how should I reach higher elements in the hierarchy from the lower elements.

What is the best solution for this?

1

There are 1 best solutions below

1
On BEST ANSWER

In C: GetB().GetA().DoSomething()

C's DoSomething() calls B's DoSomething() which calls A's DoSomething.

I think both are wrong because from architectural standpoint such approach creates strong coupling between the classes. Consider using event dispatcher, that implements the Observer pattern for your logic. Let components send events to each other as well as react to them.

I am not sure about how will this work performance-wise in your case, but I strongly advise against premature optimization unless it's evident.