Consider this file, first.cpp
, containing a class definition and use:
#include <iostream>
struct Foo
{
Foo(){ std::cout << "Foo()" << std::endl; }
~Foo(){ std::cout << "~Foo()" << std::endl; }
};
int main(){
Foo f;
return 0;
}
and another, second.cpp
, containing a conflicting class definition:
#include <iostream>
struct Foo
{
Foo();
~Foo();
};
Foo::~Foo(){ std::cout << "wrong ~Foo()" << std::endl; }
The linker complains about duplicate symbols when there are two functions with the same names defined, but these files with duplicate class methods compile without an error.
I compiled with these commands:
$ g++ -c second.cpp -o second
$ g++ second first.cpp -o first
Reordering the arguments to the second g++
call doesn't change the output.
And when first
is run, this is the output:
$ ./first
Foo()
wrong ~Foo()
Why does the linker allow duplicate class methods? If it's apparently allowed, why is wrong ~Foo()
printed?