0

When learning C++, the books always create structs as follows:

struct X{
    int a;
};

X y; 
X *yp; // pointer to object of X class

But I've seen some C++ code online where people instead use the following syntax:

struct X y;
struct X *yp;

Why do they add the struct in front and is there any difference between the two methods of creating objects of X class.

user22119
  • 717
  • 1
  • 4
  • 18

2 Answers2

1

In C++ (as opposed to C) you can mostly just write X when X is a struct type. You still need to write struct X

  • for disambiguation in some rare cases, and
  • when X has not yet been declared.

Examples of the last point:

  • in a friend declaration,
  • as an id type for a template,
  • with the usual PIMPL idiom .

Example of the first point:

struct A {};
void A() {}

auto main() -> int
{
    void (*f)() = &A;
    //A x;  // !nyet
    struct A x;
}
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
1

This is a heritage from C. In C, the following code:

struct Foo
{
    int a;
};

created a struct, and put its tag "Foo" in its own 'tag-namespace'
the only way to access it was to do:

struct Foo foo;

Or, more common:

typedef struct Foo Foo;
Foo foo;

However, in C++ the tag is not just placed in a separate tag-namespace, but also
in the enclosing namespace. But for backwards compatibility, it still allows you to
access it using struct Name

There is an additional use of the construct struct Name, both in C and C++
and that is a forward declaration:

struct Later;

Later is here an incomplete type, you can use it only for things that does not
need to know its size (such as creating a pointer)

sp2danny
  • 7,488
  • 3
  • 31
  • 53