Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize and return a struct in one line in C++

Tags:

c++

struct

I know that you can initialize structs using list syntax:

struct Foo f = {a, b, c};
return f;

Is it possible to do this in one line as you would with classes and constructors?

like image 299
John C Avatar asked Jun 20 '10 17:06

John C


People also ask

How do you initialize a structure in C?

Structure members can be initialized using curly braces '{}'. For example, following is a valid initialization.

Can you initialize values in a struct?

No! We cannot initialize a structure members with its declaration, consider the given code (that is incorrect and compiler generates error).

How do you instantiate a struct without new?

Like a class, you can create an instance of a struct using the new keyword. You can either invoke the default parameterless constructor, which initializes all fields in the struct to their default values, or you can invoke a custom constructor.


1 Answers

If you want your struct to remain a POD, use a function that creates it:

Foo make_foo(int a, int b, int c) {
    Foo f = { a, b, c };
    return f;
}

Foo test() {
    return make_foo(1, 2, 3);
}

With C++0x uniform initialization removes the need for that function:

Foo test() {
    return Foo{1, 2, 3};
    // or just: 
    return {1, 2, 3};
}
like image 51
Georg Fritzsche Avatar answered Oct 12 '22 07:10

Georg Fritzsche