14

To declare a class object we need the format

classname objectname;

Is it the sameway to declare a structure object?

like

structname objectname;

I found here a structure object declared as

struct Books Book1;

where Books is the structure name and Book1 is its object name. So is there any need of usinge the keyword struct before declaring a structure object?

Hari Krishnan
  • 5,992
  • 9
  • 37
  • 55

3 Answers3

26

This is one of the differences between C and C++.

In C++, when you define a class you can use the type name with or without the keyword class (or struct).

// Define a class.
class A { int x; };

// Define a class (yes, a class, in C++ a struct is a kind of class).
struct B { int x; };

// You can use class / struct.
class A a;
struct B b;

// You can leave that out, too.
A a2;
B b2;

// You can define a function with the same name.
void A() { puts("Hello, world."); }

// And still define an object.
class A a3;

In C, the situation is different. Classes do not exist, instead, there are structures. You can, however, use typedefs.

// Define a structure.
struct A { int x; };

// Okay.
struct A a;

// Error!
A a2;

// Make a typedef...
typedef struct A A;

// OK, a typedef exists.
A a3;

It is not uncommon to encounter structures with the same names as functions or variables. For example, the stat() function in POSIX takes a struct stat * as an argument.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
  • 1
    Thanks for a great answer. One question: [this answer](https://stackoverflow.com/a/8423005/10027592) says that even C++ *requires* the `struct` keyword in your example (`stat()` function in POSIX systems). So, in these kinds of cases where function and structure have the same name, `struct` *must* be used even in C++? – starriet Jul 23 '22 at 13:36
  • 1
    @starriet: Yes. The difference is that in C++, `struct` may be omitted in other scenarios. – Dietrich Epp Jul 23 '22 at 15:01
10

You have to typedef them to make objects without struct keyword

example:

typedef struct Books {
     char Title[40];
     char Auth[50];
     char Subj[100];
     int Book_Id;
} Book;

Then you can define an object without the struct keyword like:

Book thisBook;
Sajad
  • 492
  • 2
  • 10
5

Yes. In case of C language, you need to explicitly give the type of the variable otherwise the compiler will throw an error: 'Books' undeclared.(in the above case)

So you need to use keyword struct if you are using C language but you can skip this if you are writing this in C++.

Hope this helps.