• 11
• 14
• 19
• 27
• 9

# Clarification needed...

This topic is 3686 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Ok after google, and reading, and more reading, and books, I am stuck. What is the real difference between structs and enums in C++? They both look to do the same thing but obviously theres a difference in there.

##### Share on other sites
Structs are different from enums. In fact, they are more like classes than enums. See, a struct can contain many different types of variables (they can also contain constructors etc...). An enum is a data type that has a number of identifiers. An enum is used to identify different variable types and the value will always be a number. A struct, however, has many data types that can be different. For example, you could have two int variables and a char and a bool in one struct. There is no way of doing this with an enum, because an enum is an abstract data type rather than an object that can contain many variables. I hope that cleared things up (instead of confused you even more!)

##### Share on other sites
You can think of an enum as almost being the same thing as an int - except that it has a limited range of valid values.

e.g. Here I define an enum (which is like an int), which can only hold the values 'foo', 'bar' or 'baz' (which you can think of as 0, 1 and 2).
enum myEnumType{  foo,// 0  bar,// 1  baz // 2};myEnumType myVariable = foo;myVariable = 6;//Error - enums are almost the same as ints, but only let you use the enumerated names, not direct numeric values!
It is possible to convert between enums and ints, though it's not guaranteed to work (depending on your compiler), so it's best not to do things like this:
myVariable = (myEnumType)(2);//convert an int to a myEnumType if( myVariable == baz )  cout << "My cast from int to myEnumType worked!";

Internally, you can imagine that the compiler is converting your code to something like this:
typedef int myEnumType;const int foo = 0;const int bar = 1;const int baz = 2;or#define myEnumType int#define foo        0#define bar        1#define baz        2

Structs on the other hand are almost exactly the same as classes - they group lots of variables into one big block of variables.
struct myStructType{  int a;  int b;  float c;};myStructType myVariable;myVariable.a = 42;myVariable.b = myVariable.a / 2;myVariable.c = myVariable.b * 123.45f;