Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to initialise a new struct variable that does not involve writing a constructor?

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:

  • Is there some new mechanism to achieve this without writing a constructor in the struct "test"?
  • If so, what is it called (so I can read more about it).

If this "feature" does not exist then please put me out of my misery!, it could be that my imagination has made this up...

like image 471
code_fodder Avatar asked May 22 '18 17:05

code_fodder


People also ask

Do I need a constructor for a struct?

Technically, a struct is like a class , so technically a struct would naturally benefit from having constructors and methods, like a class does.

How do you initialize a new struct?

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.

Can struct have empty constructor?

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.

How do you initialize a struct variable in C++?

// In C++ We can Initialize the Variables with Declaration in Structure. Structure members can be initialized using curly braces '{}'.


1 Answers

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
like image 138
M.M Avatar answered Sep 20 '22 23:09

M.M