Question

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

Was it helpful?

Solution

Consider template method as a replacement for the infamous flags.

OTHER TIPS

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.

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.

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)

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top