C++ Logo

std-proposals

Advanced search

[std-proposals] c++ proposal

From: Ruud Rietvink <ruud_at_[hidden]>
Date: Tue, 30 Jun 2026 18:18:13 +0200
C++ object initializer and finalizer
====================================

In the constructor and destructor of an object you cannot use virtual
methods properly.
So calling a virtual method in a base class to get some possible derived
value is not possible.

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

Initializer is also called after copy construction.


Example:
    class Base
    {
    protected:
        ...
        virtual const char* const logName() = 0;

        +Base() { logStart(logName()); }
        virtual -Base() { logEnd(logName()); }
        ...
    };


    class Derived: protected Base
    {
    protected:
        ...
        const char* const logName() override { return "Derived"; }
        +Derived() { // After +Base } // Optional, otherwise
default
        -Derived() override { // Before -Base } // Optional
        ...
    };


    Base* base = new Derived();
    ...
    delete base;


    // Order:
    //
    // Base()
    // Derived()
    // Object intact.
    // +Base() (same order as constructor chain)
    // +Derived()
    // Life...
    // -Derived() (same order as destructor chain, for all
implementations of -class())
    // -Base()
    // Object still intact.
    // ~Derived()
    // ~Base()

Received on 2026-06-30 16:18:18