Different behavior of C++ with default value for public vs private scope

  1. The member is private, you get the error where you’re trying to print it, outside of the class.

  2. Simple enough, first all of the default values are assigned (constructed, see comment), then the code inside the constructor is executed. That’s why you see the 5 inside the constructor.

If you want the constructor to change the initialization value of a, you can use an initializer list:

Test(): a{0}
{
    cout<<a<<endl;
    cout<<"default const";
}

And this would print 0, the value of a will never be 5 when using this constructor.

Leave a Comment