Reputation: 23052
Suppose I have this type:
struct T
{
SomeType a;
OtherType b;
};
I think there is some way to declare an object of type T
and defining the initialised values of a
and b
in line, but I can't remember how this worked, or even what it's called so I can look it up. Something like T t(a, b)
where a
and b
are of type SomeType
and OtherType
respectively.
How do I achieve this without declaring a constructor, and what is it called?
Upvotes: 1
Views: 255
Reputation: 9991
You can write T t = {a, b}
. That only works with PODs aggregates though (or with a propper constructors of course).
Upvotes: 4
Reputation: 135
C++11 suports unified inicializatoin list with "{}", which means you can init. classes with "{}" as a struct before you can initialize the the struct like this
T t{someTypeA, otherTypeB};// someTypeA and someTypeB must be defined
here is a simple test code
#include <iostream>
using namespace std;
class B
{
public:
int a;
};
class C
{
public:
int a;
};
struct A
{
B b;
C c;
};
int main(int argc, char** argv)
{
B b;
C c;
b.a = 1;
c.a = 2;
A a{b, c};
cout << a.b.a << a.c.a << endl;
return 0;
}
Upvotes: 0
Reputation: 25603
You tagged with c++11, so do very simply this:
#include <iostream>
struct T
{
int a;
float b;
};
int main()
{
T t{1,2.2};
std::cout << t.a << ":" << t.b << std::endl;
}
Upvotes: 3