I think that I vaguely recall that one of the newer c++ standards (maybe its c++11, or maybe 14?...17??) allows you to initialise a struct, whereby you can define a struct and then initialise it without having to write a constructor.
E.g.:
struct test
{
int a;
int b;
std::string str;
};
int main()
{
std::map<int, test> test_map;
test_map[0] = test(1, 2, "test1"); // This is the line in question
// Or it might be more like: test_map[0] = test{1, 2, "test1"};
return 0;
}
I can't recall the name of this special initialisation (or if it even exists)!. So my questions are:
If this "feature" does not exist then please put me out of my misery!, it could be that my imagination has made this up...
Technically, a struct is like a class , so technically a struct would naturally benefit from having constructors and methods, like a class does.
2 ways to create and initialize a new structThe new keyword can be used to create a new struct. It returns a pointer to the newly created struct. You can also create and initialize a struct with a struct literal. An element list that contains keys does not need to have an element for each struct field.
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 C++ We can Initialize the Variables with Declaration in Structure. Structure members can be initialized using curly braces '{}'.
The "initialize without a constructor" is called aggregate initialization, it has always been a part of C++ since day 1. Unfortunately, some might say.
In C++98 you could write:
std::map<int, test> test_map;
test temp = { 1, 2, "test1" };
test_map[0] = temp;
C++11 added that you can use aggregate initialization in prvalues, so you do not need to declare the intermediate variable (and there are no extra copies):
std::map<int, test> test_map;
test_map[0] = { 1, 2, "test1" };
std::map<int, test> m2 = { {0, {1, 2, "test2"}} }; // and this
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