I read a lot of answers saying that one must initialize a const class member using initializing list. e.g. how-to-initialize-const-member-variable-in-a-class But why my code compiles and runs correctly?
class myClass
{
public:
myClass()
{
printf("Constructed %f\n", value);
}
~myClass()
{
printf("Destructed %f\n", value);
}
const double value = 0.2;
};
void test(const std::shared_ptr<myClass> &ptr)
{
std::cout << "in test function" << std::endl;
std::cout << ptr->value << std::endl;
}
int main()
{
std::shared_ptr<myClass> ptr = std::make_shared<myClass>();
test(ptr);
std::cout << "finished" << std::endl;
}
output
Constructed 0.200000 in test function 0.2 finished Destructed 0.200000