c++ global access related
Hi All,
In a class , I have Init() method, which gets called if that feature is enabled.
But somehow, i want to make sure that other methods are called, only if Init() is called earlier.
Right now, eventhough Init() is not called, other methods are called and resulting in bad behaviour.
What is best way to implement this ? May be add a static flag in the class and check it at each method call.
Could c++ experts let me know the better way to implement this ?
thanks
pdk
Re: c++ global access related
Quote:
May be add a static flag
Why a static flag? Does init() set class static variables? Why can't initialisation be done in the class constructor?
Re: c++ global access related
Quote:
Originally Posted by
pdk5
Hi All,
In a class , I have Init() method, which gets called if that feature is enabled.
But somehow, i want to make sure that other methods are called, only if Init() is called earlier.
Right now, eventhough Init() is not called, other methods are called and resulting in bad behaviour.
What is best way to implement this ? May be add a static flag in the class and check it at each method call.
Could c++ experts let me know the better way to implement this ?
thanks
pdk
Add a boolean member variable, set it to false in all class ctors.
Your Init() is now supposed to reset this member to true.
Then each other method is supposed to check this member and return immediately if it is not true.
Re: c++ global access related
Quote:
Originally Posted by
pdk5
Right now, eventhough Init() is not called, other methods are called and resulting in bad behaviour.
If the other methods belong to the same class as Init() you can use the State pattern, a common OO design pattern,
https://en.wikipedia.org/wiki/State_pattern
The State pattern is a way to allow an object to change its behavior at runtime. In this case you would have two states, one initial and one after Init() has been called. In the initial state the methods do nothing so if they're called nothing happens. When Init() is called it first performs the initialization but then it also switches states so the methods start doing what they're supposed to do.
The advantage of this approach is explained in the third paragraph of the link I posted.
The OO implementation is somewhat involved and you could off course accomplish the same thing by simply introducing an internal boolean variable indicating whether Init() has been called or not. Since there are just two states and this is unlikely to change that may very well be the best way to do it. I just wanted to mention that there is a the standard OO way to do this indeed.
Re: c++ global access related
sorry kaud and others , was away on some urgency.
But the class is nested one, it is bit complex than one i shown..i;ll study further. (homework for me)
Thanks a lot for all i/ps