There is this code:
file a.hpp:
class A;
file a.cpp:
#include "a.hpp"
struct A {
int x = 777;
int y;
};
A a_zew;
file main.cpp:
#include "a.hpp"
#include <iostream>
class A { // definition of class A is different than above
public:
int x;
};
int main() {
A a; // definition of class A in main.cpp
extern A a_zew; // definition of class A in a.cpp
std::cout << a_zew.x << std::endl; // 777
std::cout << a.x << std::endl; // junk
return 0;
}
So class A
is defined both in file main.cpp and a.cpp and there are also two objects of these classes defined in each translation unit. Definition in both translation units of class A
is different but this code compiles. However one definition rule says that there can be many definitions of the type in the program (but only single in each translation unit) and these definitions should be the same. So why does this code compile even if definition of class A
is different in both files?