Search code examples
c++templatesvirtualabstract

How to create a C++ virtual function in abstract class allowing to return any kind of type


I've coded an abstract class A.

Is there a possibility to create a virtual function value(), which will return "whatever" and when we create a derived class B implement here function value() and return from it anything?

Here is an example and an explaination of my intent:

class A {
    public virtual void value() = 0;
};

template < class T >
class B : public A {
    private T content;
    public T value() { return content; };
};

As you can see I'm trying to create an universal container, which could be used especially in that case:

std::vector< A > container;
B< int > bint;
B< std::string > bstring;
B< zoo::monkey > bmonkey;
container.push_back( bint);
container.push_back( bstring );
container.push_back( bmonkey );

Is there a solution to this or is there other, better solution?

Thank you in advance.


Solution

  • The return types of overrides must be co-variant to that of the base class function.

    A co-variant type can be "replaced" by the compiler with that of another type. What this means for you is that the base class needs to return something, and the override must return something convertible to that.

    In your case, you're returning void from the base, and nothing but void is co-variant with void -- therefore, as written, only a void can be returned from the derived class method.

    Since you are trying to write a generic class that can be used to store "anything" in a container, I'd suggest you look in to Boost.Variant or Boost.Any. Writing a variant-type class from scratch is surprisingly difficult, and is a wheel that's already been invented.