#include <iostream> using namespace std; #include "other_library.h" struct Foo { Foo() { cout << "class\n"; } }; int main() { Foo(); // or Foo() in any expression }
This infers class , or we think. The problem is that if other_library.h has a function called Foo whose return type is suitable for displaying in any expression that we used Foo , then it quietly changes behavior, for example:
int Foo() { cout << "func\n"; return 1; }
calls func output without changing the code in main . This is bad because of the potential for insidious and hard to detect errors; even if it is not the malicious intent of other_library , a clash of names may go unnoticed.
What is a good way to deal with this problem? It was originally raised by Dan Saks in 1997 , and one proposed resolution is that all classes must be typedef'd:
typedef struct Foo Foo;
since the compiler must report a collision between the typedef name and the function name. However, this is not common practice - why not?
Clarification: This question is about good practices for our code to stop this undetected behavior change without noticing us. (In contrast to how to solve the problem, when we realized that this was happening, it was easier - for example, to rename our class).
source share