Re: How to initialise member variable in template construction
Angus <anguscomber@gmail.com>, on 01/09/2010 14:55:46, wrote:
On 1 Sep, 22:51, "Francesco S. Carta"<entul...@gmail.com> wrote:
Angus<anguscom...@gmail.com>, on 01/09/2010 14:43:29, wrote:
I am trying to set the strategy (algorithm) used in a context by
template. Here is my context class (which is incorrectly
implemented):
template<class TStrategy>
class Context //TStrategy is the algorithm
{
private:
TStrategy * strategy_; //knows about StrategyInterface
public:
void execute() const
{
strategy_->execute();
}
};
The strategies:
class StrategyInterface
{
public:
virtual void execute() const = 0; //abstract class - interface
only
};
//the actual concrete algorithms
class ConcreteStrategyA: public StrategyInterface
{
public:
virtual void execute() const
{
cout<< "Called ConcreteStrategyA execute method"<< endl;
}
};
And I want to do something like this:
Context<ConcreteStrategyA> contextD;
contextD.execute();
But I need to initialise the context data member properly. how do I
do that?
I'm not sure about "how" you would do that, but I know "where" you
should do that: in a constructor. There is none in the code you posted, why?
<please snip signatures>
I guess I just need to add this:
Context(){ strategy_ = new TStrategy; }
~Context() { delete strategy_; }
Could I do it without using the heap?
Sure, just change the private "TStrategy * strategy_;" member to
"TStrategy strategy_;" and change the "->" accesses to the "." notation.
If TStrategy needs some parameter passed to its constructor, use the
initialization list, for example:
Context() : strategy_(42) {}
or also:
Context(sometype param) : strategy_(param) {}
depending on the various details.
From there on, every Context will have a TStrategy instance as a data
member, which will be destroyed along with the Context instance that
contains it.
If that's not what you need, you can get along with the dynamic
allocation as you have posted, it all depends on your needs and the
actual implementation of the various parts.
--
FSC - http://userscripts.org/scripts/show/59948
http://fscode.altervista.org - http://sardinias.com