tags:

views:

130

answers:

1

I know the code is missing (Someone will give negative numbers). But I only want to know how do you solve constructor injection in this situation?

class PresenterFactory
{
public:
  template<class TModel>
    AbstractPresenter<TModel>*
    GetFor(AbstractView<TModel> * view)
    {
      return new PresenterA(view, new FakeNavigator());
    }
};

class ViewA : public AbstractView<ModelA>
{
  static PresenterFactory factory;
public:
  ViewA(AbstractPresenter<ModelA> *presenter = factory.GetFor<ModelA>(this)) :
    AbstractView<ModelA> (presenter)
  {
  }

  // this one is also not working
  // invalid use of ‘class ViewA’
  //  ViewA()
  //  {
  //    this->ViewA(factory.GetFor<ModelA> (this));
  //  }
};
+4  A: 

Why not to use two constructors?

// constructor with one argument
ViewA(AbstractPresenter<ModelA> *presenter) : AbstractView<ModelA> (presenter)
{
}

// constructor without arguments
ViewA() : AbstractView<ModelA>(factory.GetFor<ModelA>(this))
{
}

By the way, this pointer is valid only within nonstatic member functions. It should not be used in the initializer list for a base class. The base-class constructors and class member constructors are called before this constructor. In effect, you've passed a pointer to an unconstructed object to another constructor. If those other constructors access any members or call member functions on this, the result will be undefined. You should not use the this pointer until all construction has completed.

Kirill V. Lyadvinsky
that's it. thanks :)
jack london
Excellent point regarding 'this'. Its not always bad to pass 'this' into base classes, however this is a good example of a dangerous example. The base class sub object passed into 'GetFor' will be uninitialized, so if the constructor of "PresenterA" tries to read or modify any data in 'view' then it will read rubbish and anything it writes will most likely be lost when the constructor for AstractView<ModelA> is eventually called.
Richard Corden
Even though some compilers will warn about it, it's perfectly valid to pass around `this` in the constructor initializer list. The key is that it shouldn't be *used* in any of the constructor code. But sometimes it's necessary, e.g. to pass it somewhere else to initialize a reference member.
Tom