Search code examples
c++classlinkerlinkage

Can you have two classes with the same name and the same member function in different translation units?


Suppose I have two translation units:

//A.cpp
class X
{
};

//B.cpp
class X
{
   int i;
};

Is the above program well-formed?

If not, no further questions. If the answer is yes, the program is well-formed (ignore the absence of main), then the second question. What if there is a function with the same name in those?

//A.cpp
class X
{
    void f(){}
};

//B.cpp
class X
{
    int i;
    void f(){}
};

Would this be a problem for the linker as it would see &X::f in both object files? Are anonymous namespaces a must in such a situation?


Solution

  • Is the above program well-formed?

    No. It violates the One-Definition Rule:

    [basic.def.odr]

    There can be more than one definition of a

    • class type ([class]),
    • ...

    in a program provided that each definition appears in a different translation unit and the definitions satisfy the following requirements. Given such an entity D defined in more than one translation unit, for all definitions of D, or, if D is an unnamed enumeration, for all definitions of D that are reachable at any given program point, the following requirements shall be satisfied.

    • ...
    • Each such definition shall consist of the same sequence of tokens, where the definition of a closure type is ...
    • ...

    Are anonymous namespaces a must in such a situation?

    If you need different class definitions, they must be separate types. A uniquely named namespace is one option, and an anonymous namespace is a guaranteed way to get a unique (to the translation unit) namespace.