Short version
Well, no... C++ bases on assumption that every name in a namespace is unique. If you break that assumption you have 0 guarantee it will work.
For example if you have methods with the same name in two translation units (*.o
files). Linker wont know which one to use for given call so it will just return an error.
Long version
... but actually yes!
There is actually quite a few situation when you could get away with classes/methods with the same name.
Do not actually use any of these tricks in your programs! Compilers are free to do pretty much anything if they think it will optimize the resulting program so any of the assumption bellow may break.
Classes are the easiest. Let's take some class with only non-static members and no functions. Such a thing don't even leave any trace in the compiled program. Classes/structs are only tools for a programmer to organize data so there is no need to deal with memory pools and offsets.
So basically if you have two classes with the same name in different compilation units, it should work. After the compiler is done with them, they will consist of just a few instruction of how much to move a pointer in memory to access a specific field.
There is hardly anything here that would confuse the linker.
Functions and variables (including static class variables) are more tricky because compiler often creates symbols for them in the *.o
file. If you're lucky linker may ignore them if such a function/variable is not used but I wouldn't even count on that.
There are ways, though, to omit creating symbols for them. Static global elements or ones in anonymous namespaces are not visible outside their translation units so linker shouldn't complain on them. Also, inlined functions don't exist as separate entities so they also don't have symbols, which is especially relevant here because functions defined inside classes are inlined by default.
If there is no symbol, linker won't see a conflict and everything should compile.
Templates are also using some dirty tricks because they are compiled on demand in each compilation unit that uses them but they end up as a single copy in the final programs. I don't think this is the same case as multiple different things with the same name so let's drop the topic.
In conclusion, if your classes don't have static members and they do not define functions outside of their bodies, it may be possible to have two classes with the same name as long as you don't include them in the same file.
This is extremely fragile, though. Even if it works right now, a new version of the compiler may have some fix/optimization/change that would broke such program.
Let alone the fact that includes tends to be pretty interwoven in bigger projects so there is decent chance that at some point you will need to include both files in the same place.