user57175
user57175

Reputation: 3434

Communication between inherited classes

I have 3 classes in different files:

   X
   |
-------
|     |
Y     Z

I will be creating several objects of inherited classes Y and Z.

A specific function in class Z should be executed only if some flag variable is set by class Y.

Where should I create this flag variable (which class) and what should be the declaration be like (static/extern)?

Upvotes: 0

Views: 861

Answers (5)

Max
Max

Reputation: 3180

I think this is a weird design; you will create dependencies between inherited classes.

The method (and flag variable) should be in the parent class X.

(edit) to refine/replace what I wrote above, the variable could be in the base class, the Y class will set the variable (Setter) and the Z class will have the method which will "Get" the value from the base class.

Upvotes: 1

MSalters
MSalters

Reputation: 179877

What if you have two Y objects, and only one has the flag set? Which of your three Z objects are affected? The question suggests your design is flawed.

Upvotes: 0

RvdK
RvdK

Reputation: 19790

Best answer: what Anton Gogolev says, use templates.

(Else use a private enum variable. Use for example: GetType() which returns type.x/type.y etc)

Upvotes: 0

Pete Kirkham
Pete Kirkham

Reputation: 49311

The flag should be in Z, if it's only Z that's effected by it. But the whole thing smells - flags being set by classes rather than instances. Use polymorphism rather than flags where practical.

Upvotes: 1

Anton Gogolev
Anton Gogolev

Reputation: 115751

Consider template method as a replacement for the infamous flags.

Upvotes: 6

Related Questions