C ++ Why don't structures or classes collide with variables and functions when namespaces are executed?

How do namespaces, functions and variables arise if they have the same name within the same scope, while structures / classes, when faced with the first, do not collide with variables and functions?

I could understand why, if structures / classes and namespaces collided with each other, but not with functions and variables, but I find it strange that structures / classes do not collide with variables and functions when namespaces, perhaps because they are used in the same way (: :) and both format namespace sortings that would explain that they should be different from each other (whereas the result now seems a bit inconsistent).

Example 1:

int A; struct A {}; //void A() {} //Collision with int A //namespace A {} //Collision with int A (and also struct A if int A is removed) 

Example 2:

 struct A {}; void A() {} //int A; //Collision with function A //namespace A {} //Collision with function A (and also struct A if int A is removed) 

Example 3:

 namespace A {} //struct A {}; //Collision with namespace A //void A() {} //Collision with namespace A //int A; //Collision with namespace A (and function A if namespace A is removed) 
+5
source share
1 answer

I believe why structures, as you say, do not β€œcollide” with variables, and functions - compatibility with C.

In C, a structure type must be tagged with a struct tag if it was not typedef ed. This way you have things like struct stat and stat declared in <sys/stat.h> . There is no problem with C in C, because when you type stat alone, it means a function, and when you type struct stat , it means type; there is no collision.

But what should happen when you #include <sys/stat.h> in C ++ then? It will try to declare both the structure and the function in the global scope with the same name, and in C ++ you do not need the struct keyword when accessing the type. C ++ must resolve this "collision", otherwise it would simply be impossible to include such a header in a C ++ program. In addition, there should be a rule in C ++ that when a function and a structure type declared in the same scope have the same name, this name means only the function, while the type is indicated in front of it with struct . Only then will compatibility with C. be maintained.

For classes, this is supposedly only because the classes should be identical to the structures, with the exception of the visibility of elements and databases by default. This would unnecessarily complicate the language to introduce more differences.

There is no reason to allow namespaces to have the same names as variables and functions in the same scope, since there are no namespaces in C. Therefore, this is not permitted.

+6
source

Source: https://habr.com/ru/post/1205136/


All Articles