How can I tell the inheriting class to not call its base class' parameter-less constructor?

前端 未结 7 2733
礼貌的吻别
礼貌的吻别 2021-02-19 23:32

I was surprised to find out that the parameter-less constructor of my base class is called any time I call any constructor in a derived class. I thought that is what

7条回答
  •  时光取名叫无心
    2021-02-20 00:35

    One way would be to make your base default constructor private, but that only works if you make a helper constructor in the base class that calls the private one when you need it explicitly.

    class Base
    {
      private Base() { ... special default base logic ... }
      protected Base(... params ...) : this() { ... exposed base that calls private cons ... }
      protected Base(... other params ...) /* no default call */ { ... exposed cons that doesnt call default ...}
    }
    
    class DerivedNoCall
    {
      public DerivedNoCall() : base(... other params ...) {} //<-- will NOT call default base
    }
    
    class DerivedDoCall
    {
      public DerivedDoCall() : base(... params ...) {} //<-- WILL call default base cons indirectly
    }
    

    This is really contrived, and @aakashm has the best answer.

提交回复
热议问题