1

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?

quant
  • 21,507
  • 32
  • 115
  • 211

3 Answers3

4

You can write T t = {a, b}. That only works with PODs aggregates though (or with a propper constructors of course).

Community
  • 1
  • 1
nwp
  • 9,623
  • 5
  • 38
  • 68
3

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;

}   
Klaus
  • 24,205
  • 7
  • 58
  • 113
  • 2
    Which is called aggregate-initialization. – dyp May 22 '14 at 12:09
  • As dyp said, this is aggregate initialization and works with C++03 compilers as well. It looks like you might be conflating it with C++11's list initialization. – Praetorian May 22 '14 at 20:38
  • 1
    @Praetorian In C++03, this will only work if written as `T t = {1,2.3};` – dyp May 22 '14 at 22:24
0

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; 
} 
Gavin
  • 135
  • 1
  • 4