One definition rule and various class definitions in two translation units

There is this code:

a.hpp file:

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 << ax << std::endl; // junk return 0; } 

So, class A is defined both in the main.cpp and a.cpp files , and there are also two objects of these classes defined in each translation unit. The definition in both Class A translation units is different, but this code compiles. However, one definition rule says that a program can have many type definitions (but only one in each translation unit), and these definitions must be the same. So why is this code compiled even if the definition of class A is different in both files?

+4
source share
1 answer

Your program has undefined behavior. Paragraph 3.2 / 6 of the C ++ 11 standard indicates:

A program can have more than one definition of a class type (Section 9), [...] provided that each definition appears in a different translation unit and provided that the definitions satisfy the following requirements. A given such object with the name D , defined in more than one translation unit, then [...]

And then the list of requirements that your program really violates follows. However, at the end of the list this is mentioned:

[...] If the definitions of D satisfy all these requirements, then the program should behave as if there were one definition of D If the definitions of D do not satisfy these requirements, then the behavior is undefined .

+8
source

All Articles