c++ - Forward declaration of returned type of function -


as answer suggests, know it's allowed use incomplete types return value in function's declaration. wrote following code:

obj.h

class obj {     int x; }; 

f.h

class obj; obj f(); 

f.cpp

#include "obj.h"  obj f() {     return obj(); } 

main.cpp

#include "f.h" int main() {     f();     return 0; }; 

compiling code following compiler:

g++ (gcc) 4.8.5 20150623 (red hat 4.8.5-4)

using following compilation command:

g++ *.cpp 

gives following error:

main.cpp: in function 'int main()': main.cpp:4:7: error: invalid use of incomplete type 'class obj'      f();        ^ f.h:1:7: error: forward declaration of 'class obj'  class obj;        ^ 

so compiler not allowing using incomplete type return value in function's declaration. what's explanation?

as stated "it's allowed use incomplete types return value in function's declaration". that's compiler allowed do. used incomplete return type in non-defining function declaration - declaration of f in f.h compiles without problems.

but that's allowed do. , not in way change fact that:

  1. at point of function definition return type shall complete
  2. at point of function call return type shall complete.

in code, inside main() attempt call function declared incomplete return type. hence error.

5.2.2 function call [expr.call]

10 function call lvalue if result type lvalue reference type or rvalue reference function type, xvalue if result type rvalue reference object type, and prvalue otherwise.

11 if function call prvalue of object type:

— if function call either — operand of decltype-specifier or — right operand of comma operator operand of decltype-specifier, temporary object not introduced prvalue. type of prvalue may incomplete. [...]

— otherwise, type of prvalue shall complete.

in other words, allowed introduce forward declaration of function incomplete return type. time defining function or calling it, should have return type completed.


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -