Constructor injection

I know the code is missing (someone will give negative numbers). But I just 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));
  //  }
};

      

+2


source to share


2 answers


Why not 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, a pointer this

only acts inside non-static member functions. It should not be used in the initialization list for the base class. Base class constructors and class member constructors are called before this constructor. Basically, you passed a pointer to a non-constructed object to another constructor. If these other constructors access any members or call member functions to do so, the result will be undefined. You shouldn't use this pointer until the entire construction is complete.

+4


source


public class ConstEx {

    String name;
    Integer id;
    public ConstEx(String name, Integer id) {

        System.out.println("--------Constructor Firs -------");
    }

    public ConstEx(Integer id,String name) 
    {
        System.out.println("-----Second Constructor--------");
    }
}




with th Following Configuration in xml

<bean id="const1" class="com.spring.hari.springexample.ConstEx">
        <constructor-arg type="java.lang.Integer" >
            <value>10</value>
        </constructor-arg>
        <constructor-arg type="java.lang.String" >
            <value>100</value>
        </constructor-arg>
    </bean>


Why First Constructor is called since i have mentioned the types even than it is calling first constructor

      



0


source







All Articles