Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <h2>struct inline initialization vs. inline constructors</h2> <p>Sometimes, we need in C++ a simple aggregation of data. The data being somewhat independant, protecting it through encapsulation would not be worth the effort.</p> <pre><code>// C-like code in C++ struct CRect { int x ; int y ; } ; void doSomething() { CRect r0 ; // uninitialized CRect r1 = { 25, 40 } ; // vulnerable to some silent struct reordering, // or adding a parameter } </code></pre> <p>; I see three problems with the code above:</p> <ul> <li>if the object is not specifically initialized, it won't be at initialized all</li> <li>if we echange x or y (for whatever reason), the default C initialization in doSomething() will now be wrong</li> <li>if we add a z member, and liked it to be "zero" by default, we would still need to change every inline initializing</li> </ul> <p>The code below will have the constructors inlined (if really useful), and thus, will have a zero cost (as the C code above):</p> <pre><code>// C++ struct CRect { CRect() : x(0), y(0) {} ; CRect(int X, int Y) : x(X), y(Y) {} ; int x ; int y ; } ; void doSomething() { CRect r0 ; CRect r1(25, 40) ; } </code></pre> <p>(The bonus is that we could add a operator== methods, but this bonus is out of topic, and so worth mentioning but not worth as an answer.)</p> <h2>Edit: C99 has named initialized</h2> <p>Adam Rosenfield made an interesting comment I find very interesting:</p> <p><em>C99 allows named initializers:</em> CRect r = { .x = 25, .y = 40 }</p> <p>This won't compile in C++. I guess this should be added to C++, if only for C-compatibiliy. Anyway, in C, it alleviates the problem mentioned in this answer.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload