Search code examples
c++overridingvirtualcovariance

C++ - Override virtual function and polymorphism


I think I don't get something a very basic concept on virtual behavior. I want to create the following hierarchy:

    class Parser{

       virtual Parsable parse() = 0;
    }

    class SpecialParser : public Parser{

       SpecialParsable parse() override; // implemented

    }

Where clearly SpecialParsable class inherits from Parsable.

This returns me an error because of the different signature. (SpecialParser::parse() returns SpecialParsable instead of Parsable).

Now, Parsable is clearly an abstract class and I don't want to make it possible to be instantiated. I don't understand why shouldn't be possible to do that since SpecialParsable is only a specific implementation of a Parsable.

Thanks in advance,


Solution

  • Dynamic polymorphism in C++ relies on indirection. If you return a pointer (or a reference), your example will compile and behave as expected. This is called a "covariant return type":

    class Parser {
       virtual Parsable* parse() = 0;
    };
    
    class SpecialParser : public Parser {
       SpecialParsable* parse() override; // implemented
    };
    

    live example on godbolt.org