Re: Is overriding a function of a library in accordance with C++ standard?
Lighter wrote:
Is overriding a function of a library in accordance with C++
standard?
The following code is passed by the VS 2005 and Dev C++.
#include <cstdlib>
#include <iostream>
using namespace std;
size_t strlen(const char* p)
{
return 0;
} // !!! Note this !!! The standard library function strlen is
deliberately overriden.
No, you have defined strlen in the global namespace. The standard one
is in the std namespace, and then it is in <cstring> I think not
<cstdlib>. I thought you might get a link error if it clashes with a
symbol in the C runtime library, should that be linked in, but you
obviously don't here. Wouldn't say you can guarantee that though.
int main(int argc, char *argv[])
{
system("PAUSE");
return EXIT_SUCCESS;
}
You haven't called strlen so the linker stripped it out. Thus you
wouldn't get a link error. Try using it and see what happens.
There is even no warning after compiling the code. In front of the
fact, I have to make a guess that all the C++ compilers are
conformed
to the following rules:
1) The compiler first compiles all the source file included in the
project into object files;
yes indeed.
2) At link time, the compiler first searches the object files for
all
the unresolved symbols; if it fails to find some symbols, then the
compiler will search the libraries which are included in the project
to
find the symbols.
And if it finds them twice it will fail to link.
The linker will look at main and any globals and work down the tree to
see what it needs to link in. That's why it's called linking. Anything
left on the shelf is ignored, like your strlen function.
3) If the object files containes a symbol, then the symbols that
have
the same name in the libraries will be ignored.
No they won't be, they will cause a clash, but only if the exact name
matches. Do not confuse this with compiler choosing the closest match
where the functions are different but more than one may work with the
particular parameter set, eg a template vs a non-template and an
implicit-conversion vs an exact match.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]