Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the new C++ return syntax limited?

Tags:

c++

return

c++11

I started a new private project and decided to use more C++11/14 this time. So I also started using the new return syntax

auto functionName() -> returnType; 

It works for the most part very well, but now I needed some error handling and could not find out how to re-write stuff like this:

virtual const char* what() const noexcept override; 

with the new syntax. Are there some cases where the new syntax can not be used or am I only not clever enough to find the right order? For me it is important to keep things consistent, so I hope the problem is more on my side.

like image 993
cpow Avatar asked Jul 23 '16 11:07

cpow


People also ask

What does a return function do in C?

The return statement terminates the execution of a function and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can also return a value to the calling function.

What is return * this in C++?

this means pointer to the object, so *this is an object. So you are returning an object ie, *this returns a reference to the object.

How do I return to main function in C++?

The normal exit of program is represented by zero return value. If the code has errors, fault etc., it will be terminated by non-zero value. In C++ language, the main() function can be left without return value. By default, it will return zero.


1 Answers

The reason for the problem is that noexcept is part of the function declarator (and proposed to be part of the function type in C++17), while override is an (optionally used) identifier that is not part of the function declarator.

Hence, without use of override the declaration would be

virtual auto what() const noexcept -> const char *; 

and, since override must appear after this declaration, it will result in

virtual auto what() const noexcept -> const char * override; 

That said, rather than slavishly using C++11/C++14 features, pick the ones which best reflect your intent. There is not some rule that requires only use of C++11/C++14 features if there are older alternatives to achieve the same thing.

like image 118
Peter Avatar answered Sep 21 '22 16:09

Peter