C
CodeTrooper
I am new to C++ and was trying to find if objects in C++ are
intialized by default. I wrote a sample program as follows:
#include <iostream>
int main()
{
class A
{
int a, b, c;
public:
int getVal() { return c; }
};
A obj;
std::cout << obj.getVal() << std::endl;
return (0);
}
This program prints a value of 0 when compiled with g++ and run on a
linux system. However when run in Visual Studio's C++, it crashes (but
it does not crash if I initialize obj before trying to read a member's
value.
I tried googling about the behaviour but could not find anything
definitive. I would like to know if the use of an uninitialized object
like this results in an undefined behaviour and if there is any
initialization (maybe, to zeroes) provided by default for the objects.
From the results I have, it does seem to be the former case, but would
like to double check as to what the language standard says.
intialized by default. I wrote a sample program as follows:
#include <iostream>
int main()
{
class A
{
int a, b, c;
public:
int getVal() { return c; }
};
A obj;
std::cout << obj.getVal() << std::endl;
return (0);
}
This program prints a value of 0 when compiled with g++ and run on a
linux system. However when run in Visual Studio's C++, it crashes (but
it does not crash if I initialize obj before trying to read a member's
value.
I tried googling about the behaviour but could not find anything
definitive. I would like to know if the use of an uninitialized object
like this results in an undefined behaviour and if there is any
initialization (maybe, to zeroes) provided by default for the objects.
From the results I have, it does seem to be the former case, but would
like to double check as to what the language standard says.