pss
pss

Reputation: 95

Syntax of final, override, const with trailing return types

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;
}

Upvotes: 9

Views: 4073

Answers (1)

songyuanyao
songyuanyao

Reputation: 172934

The correct syntax should be:

  1. 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;
    
  2. 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;
    }
    

Upvotes: 9

Related Questions