1

Is the following code produce defined behavior or undefined behavior. I tried it on my VC++ and I got one thing, but I'm curious to see if that is just coincendence or if it is mandated by the c++ standard.

#include <iostream>
class TestClass {
public:
    char testChar;
    double testDouble;
    int testInt;
};

int main(int argc, char** argv) {
    TestClass s = {412.1, 52};
    std::cout << s.testChar + s.testDouble + s.testInt << std::endl;
}
Cassio Neri
  • 19,583
  • 7
  • 46
  • 68
HardcoreBro
  • 425
  • 4
  • 17
  • Isn't that just POD initialization (having a weird char(412)) !? –  Aug 22 '13 at 18:33
  • @DieterLücking: The term is *aggregate-initialization* but yes, it is what most people will understand as *POD-initialization* in C++03. In C++11 things change and PODs are a completely different beast than what they were before (all C++03 POD types are C++11 POD types, but there are some C++11 POD types that are not valid C++03 POD types [members can be private], for those you cannot use *aggregate-initialization*) – David Rodríguez - dribeas Aug 22 '13 at 20:28

1 Answers1

8

The behavior is defined, but the result might not be what you expect.

The order of the fields is important. For aggregate initialization each value will initialize the next member in order of declaration, so in the code above, testChar will get the value static_cast<char>(412.1), testDouble will get value 52 and testInt will get value 0 (the standard guarantees that all members for which no value is provided will be initialized to 0.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489