Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One definition rule and different class definitions in two translation units

Tags:

c++

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?

like image 370
scdmb Avatar asked Feb 17 '23 15:02

scdmb


1 Answers

Your program has undefined behavior. Paragaph 3.2/6 of the C++11 Standard specifies:

There can be more than one definition of a class type (Clause 9), [...] in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. Given such an entity named D defined in more than one translation unit, then [...]

And what follows is a list of requirements that your program is indeed violating. However, at the end of the list, this is mentioned:

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

like image 124
Andy Prowl Avatar answered Apr 26 '23 23:04

Andy Prowl