Home > other >  Can const data members have different values between translation units?
Can const data members have different values between translation units?

Time:02-01

I'm wondering if it is permitted to declare the same class multiple times using different values for a const member, or if this would be an ODR violation? Consider this example with two independent translation units that are going to be linked into some libx library:

// x.h
#pragma once

class X {
  const int x = VALUE;
};
// x1.cpp
#define VALUE 1
#include "x.h"

int fn1() {
  X x;
  return x.x;
}
// x2.cpp
#define VALUE 2
#include "x.h"

int fn2() {
  X x;
  return x.x;
}

Also, in case this is not legal, does it make a difference whether x is declared const or not?

CodePudding user response:

Yes, different objects can have different const data members. The issue that the comments are focussing on is in the way that the data member gets initialized, which doesn't really address the issue.

struct s {
    const int x;
    s(int xx) : x(xx) {}
};

s s1(1);
s s2(2);

What you can't do is define the same name in multiple translation units with a different definition:

// a1.cpp
s s1(1);

// a2.cpp
s s1(2);

that's a violation of the one definition rule. But it has nothing to do with the const data member; the same problem would occur if s::x was not const. And you'd have an ODR violation in your original example if x was plain int, not const.

CodePudding user response:

From One Definition Rule's documentation:

There can be more than one definition in a program of each of the following: class type, enumeration type, inline function, inline variable (since C 17), templated entity (template or member of template, but not full template specialization), as long as all of the following is true:

  • each definition consists of the same sequence of tokens (typically, appears in the same header file)

So you have ODR violation in your program. Also this is independent of whether the data member is const or not.

CodePudding user response:

No.

Each such definition shall consist of the same sequence of tokens

You can can find the legalese in §6.3 [basic.def.odr]

  •  Tags:  
  • Related