0

I've seen in an article a code similar to this one:

#include <iostream>

class MyClass {
public:

  auto myFunction(int i)->void {
    std::cout << "Argument is " << i << std::endl;
  }
};

void main() {
  MyClass myClass;
  myClass.myFunction(4);
}

The program prints correctly the output Argument is 4, but I don't understand the signature of the class function member and what's its difference with the usual one. When it's useful to use this different signature rather than void myFunction(int i)?

Jepessen
  • 11,744
  • 14
  • 82
  • 149

1 Answers1

1

This is an (ab)use of the trailing-return-type syntax that has been introduced in C++11. The syntax is:

auto functionName(params) -> returnType;
auto functionName(params) -> returnType { }

It works the same as a classic function declaration with the return type on the left, except that the trailing type can use names introduced by the function's signature, i.e:

T    Class::function(param);      // No particular behaviour
auto Class::function(param) -> T; // T can use Class::Foo as Foo, decltype(param), etc.

In this case though, there is no point except consistency.

Quentin
  • 62,093
  • 7
  • 131
  • 191
  • Can consistency really be called abuse? (I mean if at least one function actually requires it) – StoryTeller - Unslander Monica Dec 29 '16 at 09:38
  • @StoryTeller your question mark is what called for the parentheses. It's a matter of taste -- I personally find the trailing type syntax harder to read, but I certainly see why it can be compelling. – Quentin Dec 29 '16 at 09:40