How to initialize a variable with {}, so a member variable in it with constructor without initialization is set to zero?

Manda Rajo 141 Reputation points
2021-10-11T09:09:49.003+00:00

My question is: Since the initialization with {} is very popular today, and how to fix the struct (vec2) so the member 'v' is set to 0?
The reason I'm talking about DirectX HLSL and Vulkan GLSL is when I want to build a shader or a compute shader, then I always first make a "C++ visualization draft" by using vec2, vec3, etc., and when the draft is perfect, I transfer my code into HLSL / GLSL.

struct vec2 {
    float x, y;
    vec2() { } // If I comment this line then an error C2512 'vec2': no appropriate default constructor available.
    //vec2() : x(0), y(0) { } // I don't like this style because in DirectX HLSL and Vulkan GLSL codes, vec2 or float2 is not initialized with 0.
    vec2(float _x, float _y) : x(_x), y(_y) {}
};

struct MyStruct {
    int a;
    int b;
    int c;
    vec2 v;
};

int main() {
    // The modern and simple initialization style but we must be careful if there's a vec2.
    MyStruct s = {}; // It sets a, b, c to 0, but v is not set to { 0 0 }.
    return 0;
}
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,834 questions
{count} votes

Accepted answer
  1. David Lowndes 4,721 Reputation points
    2021-10-11T09:59:21.603+00:00

    Try using:
    vec2() = default;

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Manda Rajo 141 Reputation points
    2021-10-11T11:12:47.637+00:00

    Thanks, I didn't believe it has a solution then I spent hour before your answer to make a very complex solution (make an additional struct vec2_initializable with an operator=), but your answer is very simple and very powerful compared to mine.

    Thanks.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.