user1429322
user1429322

Reputation: 1286

Default values for implicit Default constructor in C++

I was going through the C++ Object model when this question came. What are the default values for the data members of a class if the default constructor is invoked?

For example

class A
{
     int x;
     char* s;
     double d;
     string str;       // very high doubt here as string is a wrapper class
     int y[20];
     public :
     void print_values()
     {
         cout<<x<<' '<<s<<' '<<d<<' '<<str<<' '<y[0]<<' '<<y<<endl;
     }
}

int main()
{
    A temp;
    temp.print_values(); // what does this print?
    return 0;
}

Upvotes: 2

Views: 105

Answers (2)

Adam
Adam

Reputation: 17329

The value of an un-initialized variable is undefined, no matter where the variable lives.

Undefined does not necessarily mean zero, or anything in particular. For example, in many debug builds the memory is filled with a pattern that can be used to detect invalid memory accesses. These are stripped for release builds where the memory is simply left as it was found.

Upvotes: 1

aout
aout

Reputation: 300

You can't really predict what's going to be in your memory when you're allocating it. There could be pretty much anything as the memory you're reading has not been set to 0 (or anything else should I say). Most of the time you'll find the values to be 0 for numeric values in little executables.

Upvotes: 1

Related Questions