I was amazed when I saw that this code success compiled with MS Visual C++.
struct foo {
struct foo(int i): value(i) {}
int value;
};
What means keyword struct
in such strange context?
Constructor creation in structure: Structures in C cannot have a constructor inside a structure but Structures in C++ can have Constructor creation.
The simple answer is yes. It has a default constructor. Note: struct and class are identical (apart from the default state of the accesses specifiers). But whether it initializes the members will depends on how the actual object is declared.
A structure type definition can include more than one constructor, as long as no two constructors have the same number and types of parameters.
C# does not allow a struct to declare a default, no-parameters, constructor. The reason for this constraint is to do with the fact that, unlike in C++, a C# struct is associated with value-type semantic and a value-type is not required to have a constructor.
In most contexts, you can use the elaborated type specifier struct foo
, or equivalently class foo
, instead of just the class name foo
. This can be useful to resolve ambiguities:
struct foo {}; // Declares a type
foo foo; // Declares a variable with the same name
foo bar; // Error: "foo" refers to the variable
struct foo bar; // OK: "foo" explicitly refers to the class type
However, you can't use this form when declaring a constructor, so your compiler is wrong to accept that code. The specification for a constructor declaration (in C++11 12.1/1) only allows the class name itself, not an elaborated type specifier.
In general, you shouldn't be surprised when Visual C++ compiles all kinds of wonky code. It's notorious for its non-standard extensions to the language.
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