Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 353
Armen Tsirunyan Avatar asked Aug 17 '20 19:08

Armen Tsirunyan


People also ask

Can 2 classes contain member functions with the same name?

Yes, but only if the two classes have the same name.

Can class and function have same name?

Yes, It is allowed to define a method with the same name as that of a class. There is no compile-time or runtime error will occur.

Can 2 classes have same name in C++?

No, I don't think so that we can have multiple classes with same name in a same unit (i.e if they are and have same scope) in a program in C++. As class is a user defined data type and we cannot have two data types with same name in same unit of program.

Can classes have member functions?

In addition to holding data, classes (and structs) can also contain functions! Functions defined inside of a class are called member functions (or sometimes methods). Member functions can be defined inside or outside of the class definition.


1 Answers

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.

like image 152
eerorika Avatar answered Oct 22 '22 09:10

eerorika