I'm trying to override a virtual but also use the keywords override
, final
and const
, with trailing return type. The problem seems to be in the derived class, and the compiler error (saying that I did not specify the trailing return type) is not too helpful. The code is here: https://wandbox.org/permlink/zh3hD4Ukgrg6txyE
And also pasted below. I've played around with different ordering but still can't seem to get it correct. Any help would be appreciated, thank you.
#include<iostream>
using std::cout; using std::endl; using std::ostream;
//////////////////////////////////////////////
//Base stuff
class Base
{
public:
Base(int i=2):bval(i){}
virtual ~Base()=default;
virtual auto debug(ostream& os=cout)const->ostream&;
private:
int bval=0;
};
auto Base::debug(ostream& os) const->ostream&
{
os << "bval: " << bval << endl;
return os;
}
///////////////////////////////////////////////
//Derived stuff
class Derived : public Base
{
public:
Derived(int i=2,int j=3):Base(i), dval(j){}
~Derived()=default;
auto debug(ostream& os=cout) const override final->ostream&; // error here
private:
int dval=0;
};
auto Derived::debug(ostream& os) const override final->ostream&
{
os << "dval: " << dval << endl;
return os;
}
///////////////////////////////////////////////
//Testing!
int main()
{
Base b(42);
b.debug()<<endl;
return 0;
}
What’s This? Trailing return types are an alternative syntax introduced in C++11 to declare the return type of a function. In the old form you specify the return type before the name of the function: With the new syntax you write auto before the function name and specify the return type after the function name and parameters:
Keeping that in mind, “consistency” might be a less compelling argument for trailing return types. There are lots of programmers out there who are not yet familiar with trailing return types.
Although final isn’t used very much, override is a fantastic addition that you should use regularly. In this lesson, we’ll take a look at both, as well as one exception to the rule that virtual function override return types must match.
Especially when it comes to east/west const, trailing return types, and similar code style choices, there might be no tooling yet to do the conversion for you. Isn’t that an argument against those styles?
The correct syntax should be:
override and final should appear after the member function declaration, which including the trailing return type specification, i.e.
auto debug(ostream& os=cout) const ->ostream& override final;
override
and final
should not be used with the member function definition outside the class definition, so just remove them:
auto Derived::debug(ostream& os) const ->ostream&
{
os << "dval: " << dval << endl;
return os;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With