Consider this file, first.cpp
, containing a class definition and use:
#include
struct Foo
{
Foo(){ std::cout << \"Fo
Again, Undefined Behavior. Your program has multiple definitions for the destructor of Foo
, which means that it is in violation of the ODR. The program is wrong and anything can happend.
Why does the linker not pick it up? When a function is defined inside the class definition, it is implicitly inline
. Compilers usually mark those functions as 'weak symbols'. The linker then gets all translation units and tries to resolve the symbols. Weak symbols will be dropped by the linker if needed (i.e. if the symbol is already defined somewhere else).
As of the actual output of the program, it looks like the compiler did not actually inline the call to the constructor and thus dispatched at runtime to the symbol that was left by the linker (the non-weak one)
Why linker allows to have duplicate methods?
Because all (but at most one) are weak symbols (i.e. inline
)
Why, in this case, wrong ~Foo() is printed?
Because the call was not inlined, and the linker dropped the weak symbol