I am trying to understand why is this code block below, compile if i change the access control to public.
#include <iostream>
class Test
{
const int i;
};
int main()
{
Test a{};
return EXIT_SUCCESS;
}
What are reasons causing to compiled/error in either cases. Detailed explanation would help.
Thanks in advance.
CodePudding user response:
All non-static const
class members must be initialized by the class's constructor. This is fundamental to C .
A const
class member, therefore, results in the class's default constructor getting deleted. The class has no default constructor.
However, aggregate initialization is still possible with public const
class members, they can be aggregate-initialized. So that's allowed. a{};
is aggregate initialization, with i
default-initialized to 0.
CodePudding user response:
The fundamental behind constant is, the variable cannot be altered later (modified).
So, it is always good practice to initialize when a constant variable declared.
When you change the access specifier to public it compiles by default initialized. But what is the use of it, as you cannot modify the value.
class Test
{
const int i = 8; //EXAMPLE. This works irrespective of access specifier.
};