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

Viewed 10870

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.

6 Answers

Another option, based on the suggestion from @Konrad is to have a static method to construct the object, e.g.:

class Derived {
public:
    Derived(int p1, int p2, int p3) : Base(p1, p2) { }

    static Derived* CreateDerived(int p3) { return new Derived(42, 314, p3); }
};

Ive found this useful when extending a class from a library and having multiple parameters to override. You can even make the constructor private

Related