简体   繁体   中英

Derived Class of Abstract Base Class does not correctly override Base pure virtual method

So I am trying to create a derived class of an Abstract Base class, but the pure virtual methods cannot be declared using the Derived class.

template<class T>
class Foo
{
    public:
        virtual Foo<T>* add(const Foo<T>* rhs) = 0; 
};

template<class T>
class Doo : public Foo<T>
{
    public:
        Doo<T>* add(const Doo<T>* rhs)
        {
            return this;
        }
};

int main()
{
    Doo<double> d;
    return 0;
}

I expected the add method declaration in Doo to work because Doo is a subclass of Foo , but g++ says that I am not overriding Foo's add method. I am assuming that this something simple with how I am declaring Doo's add method.

The signatures don't match so you don't override anything. Look up the override keyword to get your compiler to help you diagnose errors like this.

add(const Foo<T>* rhs)

is not the same as

add(const Doo<T>* rhs)

They take different arguments.

They also return different types. But return types do not matter in overload resolution or when overriding, but it's usually also a sign that you are missing the mark (of what you want to override), since usually you want your overriding function to return the same type as what it overrides.

By using a function with different signature you have hidden the function instead of overriding it.

The best way to guard yourself against those errors is to use override keyword as following (in your example) every time you intend to override a virtual function:

Doo<T>* add(const Doo<T>* rhs) override

And than compiler will issue an error if the function does not actually override.

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