简体   繁体   中英

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,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM