0

I am getting compilation error C4700: uninitialized local variable 'obj' used as expected on below code because variable x and y are not initialize.

#include <iostream>
class Object
{
public:
    float x;
    float y;
};
int main()
{
    Object obj;
    std::cout << obj.x << std::endl;
    std::cout << obj.y << std::endl;
}

But for following program is compiling successfully with garbage outputs on console.

#include <iostream>
class Object
{
public:
    float x;
    float y;
public:    
    float GetX(){return x;}
    float GetY(){return y;}
};
int main()
{
    Object obj;
    std::cout << obj.GetX() << std::endl;
    std::cout << obj.GetY() << std::endl;
}

Now question is x, y are still uninitialized but compiler doing partiality in second case. can someone will elloborate more this?

user1035089
  • 53
  • 3
  • 8
  • 2
    Just because the compiler compiled a program without any warnings or errors does not mean that the program is correct. Additionally, C++ does not require the compiler to report a diagnostic for undefined behavior. This is undefined behavior. Depending on the code sometimes the compiler can detect it, sometimes not, depending on the actual program. The short answer is: all bets are off. – Sam Varshavchik Dec 24 '21 at 18:37

0 Answers0