A class declaration with the word struct and vice versa

But, of course, we should not even think about such things, I know, but still it is quite interesting:

class A; //declaration struct A {...}; //definition struct B; //declaration class B {...}; //definition 

When I think about it, I donโ€™t see any problems if such a thing were really resolved (because the structure and the class are essentially the same thing). But isnโ€™t it (standard)?

MSVC receives and compiles it with a warning.

+4
source share
2 answers

This is permitted according to the standard, but as some compilers warn, this is not very useful.

I believe the warning was / was triggered by MSVC using a different name for structures and classes, which would make it even less useful ...


Upon request from @Armen:

7.1.5.3 Specific Type Specifiers, p3

... in any specified type specifier, the enum keyword should be used to refer to enumeration (7.2), the union class key should be used to refer to the union (section 9), and either the class key or class should be used to indicate the class ( section 9) declared using the class class or struct .

+8
source

In accordance with C ++ 03 Standard 9.1 - 2

"A class definition introduces a class name in the area where it is defined, and hides any class, object, function or other declaration of that name in the scope (3.3)."

Thus, it is valid according to the standard.

Playing a bit with the sample code:

 #include<iostream> class A; //declaration struct A { int i;}; //definition struct B; //declaration class B {int j;}; //definition int main() { A obj; obj.i = 10; B obj2; obj2.j = 10; std::cout<<"sizeof"<<sizeof(struct B); return 0; } 

Here is the result:

 prog.cpp: In function 'int main()': prog.cpp:6: error: 'int B::j' is private prog.cpp:13: error: within this context 

The only difference between the C ++ struct and the class is that the default access specifier for the structure is public, and for the class it is private.

So, From the example above:
In this case, the compiler treats A as structure &
B as a class

As you can see, the compiler follows the quote from the standard, and the type with the definition is what the compiler recognizes by the type of declaration.

+5
source

All Articles