Suppose I declare a new C++ struct type:
struct my_struct {
int a;
int b;
};
Can I create a new instance of this struct type by:
my_struct foo;
or
struct my_struct foo;
If both work, is there any difference?
Unlike classes, structs can be instantiated without using the New operator.
Using a Structure In C++, you do not need to use the struct keyword after the type has been defined. You have the option of declaring variables when the structure type is defined by placing one or more comma-separated variable names between the closing brace and the semicolon. Structure variables can be initialized.
An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).
The general syntax for a struct declaration in C is: struct tag_name { type member1; type member2; /* declare as many members as desired, but the entire structure size must be known to the compiler. */ };
Yes, you can use either method. The difference is that this form:
my_struct foo;
Is not legal in C, so you must use this form:
struct my_struct foo;
Which is supported in C++ for backwards compatibility with C.
Both work. The main reason the second works is compatibility with C: In C the first doesn't work. As a result, struct
s are typically typedef
ed in C and there are two different kinds of names for struct
s and typedef
s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With