Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : Automatically run function when derived class is constructed

So I recently accidentally called some virtual functions from the constructor of a base class, i.e. Calling virtual functions inside constructors.

I realise that I should not do this because overrides of the virtual function will not be called, but how can I achieve some similar functionality? My use-case is that I want a particular function to be run whenever an object is constructed, and I don't want people who write derived classes to have to worry about what this is doing (because of course they could call this thing in their derived class constructor). But, the function that needs to be called in-turn happens to call a virtual function, which I want to allow the derived class the ability to override if they want.

But because a virtual function gets called, I can't just stick this function in the constructor of the base class and have it get run automatically that way. So I seem to be stuck.

Is there some other way to achieve what I want?

edit: I happen to be using the CRTP to access other methods in the derived class from the base class, can I perhaps use that instead of virtual functions in the constructor? Or is much the same issue present then? I guess perhaps it can work if the function being called is static?

edit2: Also just found this similar question: Call virtual method immediately after construction

like image 598
Ben Farmer Avatar asked Oct 31 '22 08:10

Ben Farmer


1 Answers

If really needed, and you have access to the factory.

You may do something like:

template <typename Derived, typename ... Args>
std::unique_ptr<Derived> Make(Args&&... args)
{
    auto derived = std::make_unique<Derived>(std::forward<Args>(args));
    derived->init(); // virtual call
    return derived;
}
like image 85
Jarod42 Avatar answered Nov 12 '22 19:11

Jarod42