Reputation: 862
#include <iostream>
using namespace std;
class Example
{
public:
int _public;
friend ostream& operator<< (ostream& stream, Example& o);
protected:
int _protected;
private:
int _private;
};
ostream& operator<< (ostream& stream, Example& o) {
stream <<
"_public=" << o._public << endl <<
"_protected=" << o._protected << endl <<
"_private=" << o._private << endl;
return stream;
}
int main(int argc, char const *argv[])
{
Example e;
cout << e << endl;
return 0;
}
_public=4196960
_protected=0
_private=4196368
All the three members are uninitialized. But only the public
and private
members have garbage values in them. Why is the protected
member initialized to zero? Is there a reason for that?
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609
-std=c++11
Upvotes: 1
Views: 647
Reputation: 26810
First, note that reading uninitialized variables is undefined behavior.
You need to define a constructor for your class.
And this has nothing to do with the access specifiers. It just happens (in your case) that the protected
member is at an address which previously contained the value 0.
Also better not to use variable names starting with underscore. They are reserved. It is allowed to use them in class scope but remember not to use them in global scope.
5.10 Identifiers [lex.name]
3 In addition, some identifiers are reserved for use by C++ implementations and shall not be used otherwise; no diagnostic is required.
...(3.2) Each identifier that begins with an underscore is reserved to the implementation for use as a name in the global namespace.
Upvotes: 1