tags:

views:

68

answers:

4

i see lot of struct code like below

struct codDrives {
   WCHAR letter;
   WCHAR volume[100];
} Drives[26];

we can use variables or array something like that to store the data..

but i am not sure why use struct in the programs.

i am beginner so please for my dump question

Thank you for the time spent to me

A: 

Here's some info on structs: http://www.cplusplus.com/doc/tutorial/structures/

Also, they are useful for example returning multiple values in a function, say you need to return 3 values from a function, you can return a struct with all the 3 values inside it.

Tom Gullen
A: 

Structs can also contain methods (constructors are very useful for example). Another thing is, that with structs or classes you can define copy constructors or assignment operators which then allow you to easily copy instances of your struct, even if there are pointers inside - you take care of this in the methods of the struct and don't have to worry about it later. Moreover, this allows for a nice OOP design. There are much more benefits (but also drawbacks)...

PeterK
It contains two members - letter and volume.
anon
The OP changed that. The original question contained just one member.
PeterK
@PeterK, no it didn't, it was just badly formatted.
Péter Török
OK, won't argue with you on that. Maybe I just missed it.
PeterK
+5  A: 

Structs are inherited from C, and in C++ they are almost identical to classes. The difference is that the members of a struct are by default public, while class members are by default private.

So the typical use of structs in C++ is dummy data structures which contain no logic (only - possibly - constructors and/or necessary operators).

On a more general level, classes / structs are used to group together conceptionally related data pieces. E.g. for representing a person, you may need his/her first name, surname, gender, date of birth etc. It is convenient to define a struct containing all these pieces of data as members. Then you can store and pass around instances of this struct instead of a whole bunch of distinct variables. This makes the code cleaner, less error prone, more readable and easier to maintain.

Péter Török
A: 

One reason to use structs might be to control the size and layout of the data so it can be written to and read from disk more easily.

Another reason would be for code that is used in C programs as well as C++

David Sykes