0
votes

I've got the following fairly simple code:

    WNDCLASSEX windowClass = {0};

    windowClass.cbSize { sizeof(WNDCLASSEX) };

I would like to know why the above code does not work and the code below does:

    WNDCLASSEX windowClass = {0};

    windowClass.cbSize = { sizeof(WNDCLASSEX) };

Visual Studio 15 2017 gives me those two errors:

1: expected a ';'

2: error C2064: term does not evaluate to a function taking 1 arguments

3
That's assignment, not initialization. In C++, you use = to assign a value to a variable. - Sneftel
@Sneftel confusingly, you can also use = to initialize one. - juanchopanza

3 Answers

3
votes

You cannot initialize the same variable (windowClass) more than once and you cannot initialize the member variables in separate initialization statements.

In your case, since cbSize is the first item

WNDCLASSEX windowsClass { sizeof(WNDCLASSEX) };

That will set cbSize to sizeof(WNDCLASSEX) and the rest of the struct to 0.

0
votes

The first version "does not work" because it is syntactically nonsensical. There's no branch in C++ grammar that would be able to parse your first variant. The compiler simply has no idea what you are trying to say by that sequence of characters. So, the question is really to you: what did you try to achieve by that first version?

The second version works because it is valid C++ code. The { sizeof(WNDCLASSEX) } on the right-hand side of assignment is interpreted as creation/initialization of a temporary object of the same type as windowClass.cbSize. That temporary object is then assigned to windowClass.cbSize. I.e., since windowClass.cbSize has UINT type, your second version is interpreted as

windowClass.cbSize = UINT{ sizeof(WNDCLASSEX) };

which in practice has the same effect as

windowClass.cbSize = sizeof(WNDCLASSEX);
0
votes

Or why not go full c++?

struct WndClasssEx : WNDCLASSEX
{
    WndClassex() : WNDCLASSEX { sizeof(WNDCLASSEX) } {}

}

auto mywndclass = WndClasssEx();
DoSomethingWindowsy(&mywndclass);

See c++ standard, section [Class] (quoted here from standard draft n4527, 2015).

specifically the note on standard-layout types:

[ Note: Standard-layout classes are useful for communicating with code written in other programming languages. Their layout is specified in 9.2. — end note ]