2

I was reading about one of the strange C++ feature called Injected class name here.

I tried following simple program

#include <iostream>
class test
{
    int s{3};
    public:
    int get_s()
    { return s; }
};
int main() {
    class test::test s;  // struct test::test s; also allowed. Why???
    std::cout<<s.get_s();
}

If I replace class keyword with struct in first line of main() program still compiles & runs fine. See live demo here. Why? Shouldn't I get compiler error? Why it compiles fine?

Community
  • 1
  • 1
Destructor
  • 14,123
  • 11
  • 61
  • 126

4 Answers4

6

I believe the relevant verse is in 7.1.6.3/3 (highlighting mine, quoted here from a draft of the C++17 Standard):

Thus, in any elaborated-type-specifier, the enum keyword shall be used to refer to an enumeration (7.2), the union class-key shall be used to refer to a union (Clause 9), and either the class or struct class-key shall be used to refer to a class (Clause 9) declared using the class or struct class-key.

So either keyword can be used to stipulate the scope within which the injected class name exists, irrespective of which was used to declare/define test.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
2

struct and class are almost identical in C++. The only difference is, that members of structs are public by default while member of classes are private by default.

see complete answer here: C/C++ Struct vs Class

Community
  • 1
  • 1
Daniel
  • 1,041
  • 7
  • 13
0

class test s; or struct test s; works too.

Classes and structs in C++ are virtually the same thing.

The difference is:

struct A{
};

is like

class A{
public:
};

and

class B{
};

is like

struct B{
private:
};

Allowing you to use the struct prefix is for C compatibility and I guess it extends to class because "why not?".

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
0

I'm sorry, maybe I have misunderstood your post but there is no big differences between class and struct in C++. The main differences that I know is that by default, a struct have all field public.

There is a post talking about differences between struct and class : What are the differences between struct and class in C++?

Community
  • 1
  • 1
Lilemon
  • 29
  • 4