Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why forward declaration is allowed inside function argument list?

Tags:

c++

This code shouldn't compile in my opinion, but it seems compiler treats struct NonExistingNeverDeclaredType* argument as a forward declaration (proof). But why?

#include <iostream>

int foo(struct NonExistingNeverDeclaredType* arg) {
  return sizeof(arg);
}

int main() {
  std::cout << foo(nullptr) << std::endl;
  return 0;
}

https://ideone.com/v3XzCw

like image 307
Sukhanov Niсkolay Avatar asked Dec 15 '18 11:12

Sukhanov Niсkolay


People also ask

Why forward declaration is used?

Forward declaration is used in languages that require declaration before use; it is necessary for mutual recursion in such languages, as it is impossible to define such functions (or data structures) without a forward reference in one definition: one of the functions (respectively, data structures) must be defined ...

Can you forward-declare a nested class?

You cannot forward declare a nested structure outside the container. You can only forward declare it within the container. Create a common base class that can be both used in the function and implemented by the nested class.

Do you have to forward-declare in C++?

forward declarations are required when header files refer to each other: ie stackoverflow.com/questions/396084/…


1 Answers

This is a property of the elaborated type specifier, it will introduce a declaration if the type is not previously declared:

cppreference

If the name lookup does not find a previously declared type name, the elaborated-type-specifier is introduced by class, struct, or union (i.e. not by enum), and class-name is an unqualified identifier, then the elaborated-type-specifier is a class declaration of the class-name.

It doesn't matter whether it's inside a function argument list or not. The following code is also valid:

class foo {
    class bar *b; // bar is not previously declared
};
like image 89
llllllllll Avatar answered Nov 13 '22 08:11

llllllllll