If I write a new function that has the signature of a C library function, I expect a compile error due to the ambiguity. But, I can't understand why there is no error in the following C++ code.
#include <iostream>
#include <cmath>
using namespace std;
double sqrt(double number)
{
return number * 2;
}
int main( )
{
cout << sqrt(2.3) << endl;
cout << ::sqrt(2.3) << endl;
cout << std::sqrt(2.3) << endl;
return 0;
}
If I change the return type of sqrt() to int, then a compile error occurs due to the declaration ambiguity with double sqrt() in cmath. How is it possible to override double sqrt()? (Actually, all the cmath functions can be overridden, and I don't know why.)
The program has undefined behaviour.
[reserved.names]
1 The C++ standard library reserves the following kinds of names:
1.1) — macros
1.2) — global names
1.3) — names with external linkage
2 If a program declares or defines a name in a context where it is reserved, other than as explicitly allowed by this Clause, its behavior is undefined.[extern.names]
4 Each function signature from the C standard library declared with external linkage is reserved to the implementation for use as a function signature with both extern "C" and extern "C++" linkage, or as a name of namespace scope in the global namespace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With