views:

300

answers:

5

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

+6  A: 

Consider template method as a replacement for the infamous flags.

Anton Gogolev
+1  A: 

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.

Pete Kirkham
+1  A: 

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.

Max
A: 

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)

PoweRoy
A: 

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.

MSalters