Search code examples
c++constructordelayed-execution

Call a base class constructor later (not in the initializer list) in C++


I'm inheriting a class and I would like to call one of its constructors. However, I have to process some stuff (that doesn't require anything of the base class) before calling it. Is there any way I can just call it later instead of calling it on the initializer list? I believe this can be done in Java and C# but I'm not sure about C++.

The data that I need to pass on the constructor can't be reassigned later, so I can't just call a default constructor and initialize it later.


Solution

  • Is there any way I can just call it later instead of calling it on the initializer list?

    No, you cannot. The base class constructor must be called in the initializer list, and it must be called first.

    In fact, if you omit it there, the compiler will just add the call implicitly.

    I believe this can be done in Java and C# but I'm not sure about C++.

    Neither C# nor Java allow this either.

    What you can do, however, is call a method as an argument of the base class constructor call. This is then processed before the constructor:

    class Derived {
    public:
        Derived() : Base(some_function()) { }
    
    private:
        static int some_function() { return 42; }
    };