0

I have a sample class named class Player. With constructor the program runs successfully without initialization. However, without constructor it generates an error uninitialized local variable e used and you need to initialize it to a value say 0. I want to know why the program behaving like this and how the compiler read this one?

class Player {
public:
   float x, y; //this will not work without constructor or not being initialized
   //float x = 0, y = 0; -> works successfully without constructor

A(){}

};

int main() {
Player e;
   std::cout << e.x << e.y << std::endl;
return 0;
}
Master James
  • 318
  • 5
  • 18
  • 1
    *"program runs successfully without initialization"* - no, it does not, accessing uninitialized fields is Undefined Behavior. `//float x = 0, y = 0; -> works successfully without constructor` - no, it would cause constructor to be generated and initialize these fields – user7860670 Apr 20 '19 at 15:24
  • 1
    Just because your particular implementation and the way you currently compile your code (specific optimization level for instance) gives a certain result, does *not* mean that that result is guaranteed. If you break the rules of the language, the compiler is allowed to do *anything* with *no warnings*. You'll just get different results with different compilers, on different platforms, with different optimization flags, etc. This is known as Undefined Behaviour. To get *defined* and consistent results, you *must* follow the rules. Otherwise, all bets are off. – Jesper Juhl Apr 20 '19 at 15:27
  • @JesperJuhl Good point. ;) – Master James Apr 20 '19 at 15:40

0 Answers0