So I am pretty new to C++ and I'm trying to combine std::unique_ptr
with a named constructor returning a std::optional
. I've got the following structure:
class AbstractClass {
public:
virtual ~AbstractClass() {}
};
class ChildClassA : public AbstractClass {
public:
static std::optional<ChildClassA> construct(...) { ... }
private:
ChildClassA(...) : ...{...} { ... }
};
std::unique_ptr<AbstractClass> construct(...) {
if (...) {
return std::make_unique<ChildClassA>(...); // call ChildClassA::construct(...) here
} else {
return std::make_unique<ChildClassB>(...); // call ChildClassB::construct(...) here
}
}
I want to have a function construct()
that calls the constructor of one of the child classes depending on some value. The constructors of these child classes may fail, thus I am using named constructors returning an std::optional
as described here. construct()
should return a std::unique_ptr
to make passing of ownership explicit and prevent copying of the constructed object.
Is this possible?