class Child: public Base {.....}
class Child
{
static std::optional<Base>& Child::GetBaseInstance()
{
static std::optional<Base> instance = std::make_optional<Chid>; \\Does not work. Please help
return instance;
}
}
I'm trying to return an instance but of type of std::optional of it's base. Also should I be returning std::optional& or std::optional<Base&> if I'm trying to pass the same reference?
You cannot use
std::optionalfor references. Instead, either use a raw pointer, astd::reference_wrapper, orboost::optional(which works for references).That being said, you have another flaw in your snippet:
std::optional<Base>suffers from object slicing when constructed from aChildinstance. You can read more on that here.Note that you can also use the
nullptr-like state ofstd::unique_ptrandstd::shared_ptrto indicate the additional boolean property of your object. When dealing with class hierarchies, it often makes sense to use these smart pointers, whilestd::optionalis rather a good fit for value-type objects.