Multiple non-identical definitions the One Definition Rule

suggest change

If a class, enum, inline function, template, or member of a template has external linkage and is defined in multiple translation units, all definitions must be identical or the behavior is undefined according to the One Definition Rule (ODR).

foo.h:

class Foo {
  public:
    double x;
  private:
    int y;
};

Foo get_foo();

foo.cpp:

#include "foo.h"
Foo get_foo() { /* implementation */ }

main.cpp:

// I want access to the private member, so I am going to replace Foo with my own type
class Foo {
  public:
    double x;
    int y;
};
Foo get_foo(); // declare this function ourselves since we aren't including foo.h
int main() {
    Foo foo = get_foo();
    // do something with foo.y
}

The above program exhibits undefined behavior because it contains two definitions of the class ::Foo, which has external linkage, in different translation units, but the two definitions are not identical. Unlike redefinition of a class within the same translation unit, this problem is not required to be diagnosed by the compiler.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Undefined behavior:
* Multiple non-identical definitions the One Definition Rule

Table Of Contents
8 Arrays
11 Loops
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
71 Undefined behavior
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype