Is it possible to switch to a different base class constructor at runtime?

c++, c++11, constructor, inheritance

Solution

A static function will work fine here

struct Base {
    Base(int i);
    Base(const char *sz);
    Base(const Base&) = delete;
    Base(const Base&&) = delete;
};

struct Derived : Base {
   using Base::Base;

   static Derived construct(bool with_string) {
      if(with_string) return { "forty-two" };
      return { 42 };
   }
};

Notice that this does not require a move, nor a copy constructor. If you want to have this as a local, you need to bind it to a reference in order to avoid moving it

auto &&w = Derived::construct(true);
auto &&wo = Derived::construct(false);

Problem

Suppose I'm writing `Derived` and have to inherit from `Base`, which I don't control and has two separate constructors and a deleted copy and move constructors: ``` struct Base { Base(int i); Base(const char *sz); Base(const Base&) = delete; Base(const Base&&) = delete; }; struct Derived { Derived(bool init_with_string); }; ``` Now, depending on the value of `another_param` I have to initialize my base class using either a constructor or the other; if C++ was a bit less strict it would be something like: ``` Derived::Derived(bool init_with_string) { if(init_with_string) { Base::Base("forty-two"); } else { Base::Base(42); } } ``` (this would also be useful for all the cases where it's cumbersome to calculate values to pass to base class constructors/fields initializers in straight expressions, but I'm digressing) Unfortunately, even if I don't see particular codegen or object-model obstacles to this kind of thing, this isn't valid C++, and I cannot think of easy workaround. Is there some way around this that I'm not aware of?

Original source

Related problems