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

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

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.