everyone!
Please consider the following peace of code:
$ cat a.cpp
#include <stdio.h>
struct A
{
void foo() { printf("a.cpp: A::foo()\n");}
};
void fooA()
{
A a;
a.foo();
}
$ cat b.cpp
#include <stdio.h>
struct A
{
void foo() { printf("b.cpp: A::foo()\n");}
};
void fooB()
{
A a;
a.foo();
}
$ cat main.cpp
void fooA();
void fooB();
int main()
{
fooA();
fooB();
return 0;
}
$ g++ main.cpp a.cpp b.cpp
$ ./a.out
a.cpp: A::foo()
a.cpp: A::foo()
As you can see there is no warnings or errors from linker, but on runtime we receive not what we expected. I check it on gcc 4.8.1 and msvc 2013. With simple free functions linker will raise an error in such case. But if it a method of the class it doesn't.
Why it works like this?
Functions defined inside a class definition are implicitly inline, so you're allowed to define them in multiple translation units.
The definitions must be identical, but the compiler isn't required to diagnose that since it that would be impossible when processing one unit at a time. You broke that rule, giving undefined behaviour.
To use the same name for different entities in different translation units, you could put each in a different namespace, or an unnamed namespace which is local to the translation unit:
namespace /* optional name */ {
class A {
// whatever you want
};
}
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