Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keyword struct before constructor name

Tags:

c++

visual-c++

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?

like image 964
Felix Markov Avatar asked Jul 19 '13 12:07

Felix Markov


People also ask

Can we have a constructor for struct?

Constructor creation in structure: Structures in C cannot have a constructor inside a structure but Structures in C++ can have Constructor creation.

Does struct have default constructor?

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.

How many constructors can a struct have?

A structure type definition can include more than one constructor, as long as no two constructors have the same number and types of parameters.

Which constructor is not supported by struct?

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.


1 Answers

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.

like image 65
Mike Seymour Avatar answered Sep 30 '22 15:09

Mike Seymour