I was wondering about declarations and definitions of class methods in different translational units. I know that this is not the way to do things at all, but I think it serves as good examples for understanding about linking and compilation, so please, bear with me. =)
So I have two files: extra.cpp and main.cpp, both have a an explicit and different forward declaration of class A
. Clearly, the One Definition Rule is violated, yet it compiles and links without any complains. My question is shown in the output in the main file, and, why is it actually compiling?
extra.cpp
#include <iostream>
class A{
public:
void method1(){std::cout << "method 1 defined in class declaration in extra.cpp" << '\n';}
void method2();
};
void A::method2(){std::cout << "method 2 defined out of declaration in extra.cpp" << '\n';}
main.cpp
#include <iostream>
class A{
public:
void method1();
void method2(){std::cout << "method 2 defined in class declaration in main.cpp" << '\n';};
};
void A::method1(){std::cout << "method 1 defined out of class declaration in main.cpp" << '\n';}
int main(int argc, char const *argv[]) {
A a;
a.method1();
a.method2();
return 0;
}
/* OUTPUT
method 1 defined out of declaration in main.cpp // Ok, its defined and declared in the same translation unit,
this makes sense
method 2 defined out of declaration in extra.cpp // Why is it taking the definition on a different translation unit,
and ignoring the one in the header.
*/