2

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;
}
5
  • All are uninitialized besides the string, so can contain almost anything. Commented Oct 1, 2013 at 1:18
  • Thanks! What will the string str contain? null? Commented Oct 1, 2013 at 1:19
  • You can initialize them all within the default constructor to whatever values you want. Commented Oct 1, 2013 at 1:20
  • @Troy Thanks.I got it now Commented Oct 1, 2013 at 1:23
  • @nhgrif I understand that I could do it.But I wanted to know what happens the implicit default constructor by the compiler is invoked. Commented Oct 1, 2013 at 1:24

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

In the case of std::string the variable is defined, though. While using any other variable, in that class, may yield undefined behavior, str does not.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.