Do we have a better way of returning abstract classes in C++?

Viewed 1114

I want to start throwing some interfaces into my C++ code to make it easier for me to unit test using mocks.

The problem with this is returning abstract classes from a method in C++ is a pain. You can't return by value so you need to return a pointer or a reference.

Given all of the developments in C++ in the last six or seven years, I thought I'd ask if maybe we had a better way to return an abstract base class. An interface without the noise would look something like this, but I'm sure this isn't possible.

IBaseInterface getThing() {return DerivedThing{};}

The way that I remember doing this in the past is to use a pointer (probably a smart pointer now):

std::unique_ptr<IBaseInterface> getThing() {return std::make_unique<DerivedThing>();}

The problem with the pointer is that I'm never actually planning to take advantage of nullptr so the overhead and noise of dealing with a pointer rather than a value gains me no value as a reader.

Is there a better way that I don't know to handle this?

1 Answers
Related