0
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?

lubgr
  • 37,368
  • 3
  • 66
  • 117
rstr1112
  • 308
  • 4
  • 13
  • consider that `std::optional` is specifically for cases where you want to avoid dynamic allocation of the contained object. If thats not an issue a smart pointer can be used – 463035818_is_not_an_ai Oct 02 '20 at 10:21

1 Answers1

2

You cannot use std::optional for references. Instead, either use a raw pointer, a std::reference_wrapper, or boost::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 a Child instance. You can read more on that here.

Note that you can also use the nullptr-like state of std::unique_ptr and std::shared_ptr to indicate the additional boolean property of your object. When dealing with class hierarchies, it often makes sense to use these smart pointers, while std::optional is rather a good fit for value-type objects.

lubgr
  • 37,368
  • 3
  • 66
  • 117