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?
Yes, but only if the two classes have the 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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With