Making f() virtual is a bit confusing:

 

During construction only the base member function is called. So it could be non-virtual as well?


 

-----Ursprüngliche Nachricht-----
Von: Rainer Deyke via Std-Proposals <std-proposals@lists.isocpp.org>
Gesendet: Mi 01.07.2026 07:15
Betreff: Re: [std-proposals] c++ proposal
An: std-proposals@lists.isocpp.org;
CC: Rainer Deyke <rainerd@eldwood.com>;


On 6/30/26 18:18, Ruud Rietvink via Std-Proposals wrote:
> Proposal is to introduce an initializer method that is automatically
> called after the construction is complete,
> and a finalizer method that is automatically called before the
> destruction of an object.
> Because the finalizer is called before the destructing, the vtable is
> still correct and virtual calling will work correctly.
> Proposed names:
>     class::+class() for initializing
>     class::-class() for finalizing

This solves a real problem, but I am not convinced that it solves it
better than the idiomatic workaround, nor that the problem is common
enough to justify a change in the language.  The idiomatic workaround:

  class base {
  public:
    base(int) { this->init(); }
  protected:
    base() = default;
    virtual void f() {}
    void init() {
      this->f();
    }
  };

  class derived1 : public base {
  public:
    derived1(int n) : base(n) {
      this->init();
    }
  protected:
    derived1() = default;
    void f() override {}
  };

  class derived2 final : public base {
  public:
    derived2(int n) : derived1(n) {
      this->init();
    }
  protected:
    void f() override {}
  }

Obviously this idiom is not perfect.  The base class needs an additional
protected constructor that can't come into overload conflict with the
other constructors.  All derived classes need to remember to call init.
It requires more typing.  But this extra typing buys you quite a bit of
extra flexibility:
  - You can pass arguments to `init`.
  - You can overload `init`.
  - You can put additional statements in your constructor after `init`.
  - You can choose *not* to call `init` for some constructors.

The last two bits of flexibility might be controversial, but the first
two shouldn't be.  When I use this idiom, I *usually* end up needing
arguments from the constructor for what I do in `init`.


--
Rainer Deyke - rainerd@eldwood.com
--
Std-Proposals mailing list
Std-Proposals@lists.isocpp.org
https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals