Final, override, const syntax with return types

I'm trying to override virtual, but also use keywords override

, final

and const

, with a return type. The problem seems to be in a derived class, and a compiler error (saying I didn't specify the return type) is not very helpful. Code is here: https://wandbox.org/permlink/zh3hD4Ukgrg6txyE

And also inserted below. I've played with different orders, but still can't figure out what is correct. Any help would be appreciated, thanks.

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

      

+3


source to share


1 answer


The correct syntax should be:



  • override and final must appear after the member function declaration, which includes the specification of the return type of the return type, that is

    auto debug(ostream& os=cout) const ->ostream& override final;
    
          

  • override

    and final

    shouldn't be used with a member function definition outside of a class definition, so just remove them:

    auto Derived::debug(ostream& os) const ->ostream&
    {
      os << "dval: " << dval << endl;
      return os;
    }
    
          

+4


source







All Articles