I have two questions
1) Why can we give default value if the member is public but when it is private we are not allowed? Take below example:
#include <iostream>
using namespace std;
class Test
{
private:
int a=5;
public:
Test()
{
cout<<a<<endl;
cout<<"default const";
a=0;
}
};
int main()
{
Test x;
cout<<x.a;
}
We get below error for this:
Compile Errors :
prog.cpp: In function 'int main()':
prog.cpp:6:11: error: 'int Test::a' is private
int a=5;
^
prog.cpp:19:13: error: within this context
Whereas if I make it public as below:
#include <iostream>
using namespace std;
class Test
{
public:
int a=5;
Test()
{
cout<<a<<endl;
cout<<"default const";
a=0;
}
};
int main()
{
Test x;
cout<<x.a;
}
We get output as :
5
default const0
2) My next question is, why do we have this behavior? Also when we provide this default value, why constructor value overrides the default value provided in class?