The extra parameter will only make sense in a layer of the code section where it clear that it is a specific parameter for athe class StateB object"lives". Let me call this "application layer".
Your state pattern implementation, especially the classes Context and State, however, livelives inside some "framework layer", which does not know anything about the specific StateB and it's requirements for an extra parameter.
The straightforward solution here is to make the parameter a a member of the class StateB, which has to be initialized before Context::transition() (which is part of the framework layer) is called. The initialization has to happen somewhere inside the application layer. You have basically the following options for this:
Pass the initial parameter value in the StateB constructor - that requires each constructor call to look like
new StateB(context,initialA). That's feasible when initialA is available at all places and at the time wherenew StateBis called. In your example, this happens inside the classStateA, and it is not clear ifinitialAis accessable in that class, or a the point in time when StateB is constructed.Provide an extra setter method
StateB::setA(int initialA)and call it somewhere in the application layer where initialA is known, but, beforeContext::transitionhappens. That may require detection of whenContext::currentis of typeStateBand a downcast. It also has some risk to be forgotten to be called and it givesStateBsome mutable state.
In caseIf none of these options works for you don't want to introduce this extra member variable, you can also try thisto extend the framework in general:
Create an abstraction for "potentially extra parameters" in the framework layer, for example, an
ExtraParametersclass, and extend the signature ofState::transitionandContext::transitionby thisExtraParameters. All states which don't need this parameter for a transition should ignore it, butStateB::transitioncan extract the parameterafrom it.This will have the biggest impact on your current framework implementation, but it could be sensible when different
Statesubclasses require different forms of extra parameters. There are some different possible design alternatives forExtraParameterspossible, you have to think which abstraction may makeone makes most sense for your case.
What to choose depends on your real-world context, how many State types require what kind of parameters, and where and when the parameters are become available in the system, and where or how often they change - that is something only you know, since you left no clue for us about itthese details in thisthe question.