Your program has undefined behavior, so is wrong (because what you pass to printf
does not match the " 0x%x"
format control string, since it has the wrong type); see also this answer.
Read Lattner's blog on undefined behavior (it also applies to C++)
Notice that printf
is a C library function (so you need to #include <cstdio>
). In genuine C++11, you would use some operator <<
on std::ostream
-s, probably like
std::cout << obj1 << std::endl;
and that line won't compile (unless you define such an operator, which you should do).
To explain the actual behavior (which is non reproducible in general), you need to dive into implementation details (and you don't want to: if you did, study the source and object code of your particular program and C++ library, of your compiler, of your operating system, look into calling conventions, instruction set, ABIs, etc...). The displayed garbage value (e.g. 0xfffffff) is what happens to sit in some relevant processor register or memory location (on the call stack).
BTW, if you compiled with all warnings & debug info (e.g. g++ -Wall -Wextra -g
with GCC) you'll get a warning. I strongly recommend to enable all warnings.
Notice that a struct A{
is the same as class A{public:
so you could define some explicit constructor (which would initialize the fields) and some output operator<<
:
struct A{
int a;
int s;
A(int aa=0, int ss=0) : a(aa), s(ss) {};
};
std::ostream operator << (std::ostream&out, A a) {
out << "a=" << a << ",s=" << s;
return out;
}
But you probably should read about the rule of five notably this.