Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Multiple classes with same name

Tags:

c++

scope

class

Say I have two different cpp files. Both declare classes with the same name, but perhaps a totally different structure (or perhaps the same structure, different implementation). The classes do not appear in the header files. (As an example, suppose they are Node classes for different list classes.)

I've seen these classes conflict. Is this expected by the standard? What solutions are there to this problem?

UPDATE:

As suggested by answers/comments, anonymous namespaces are what I was looking for.

like image 439
Thomas Eding Avatar asked Jun 16 '11 22:06

Thomas Eding


People also ask

Can two classes have same name?

Yes, you can have two classes with the same name in multiple packages. However, you can't import both classes in the same file using two import statements. You'll have to fully qualify one of the class names if you really need to reference both of them.

Can 2 classes contain member functions with the same name?

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

Can we have two classes with same name C++?

CPP. In each scope, a name can only represent one entity. So, there cannot be two variables with the same name in the same scope.

Has the same name as the class in which it is declared?

Constructors often have the same name as the declaring class.


1 Answers

The standard way around this problem is to wrap the classes in different namespaces.

like image 65
Will A Avatar answered Sep 18 '22 02:09

Will A