0

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
  • 1
    Read about **in-class initializers** in your favorite [c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Jason Dec 05 '22 at 07:05
  • Note also that even though `value` is `const`, it is not a compile time constant. – Jason Dec 05 '22 at 07:06
  • [Member initialization](https://en.cppreference.com/w/cpp/language/data_members#Member_initialization) – Some programmer dude Dec 05 '22 at 07:08
  • Refer to you code standard of choice when to prefer what: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-in-class-initializer – nick Dec 05 '22 at 07:12
  • The first comment of the link in the question answers that this is possible in C++11. – chris Dec 05 '22 at 07:13
  • 2
    The advice you are reading refers to older versions of C++ (or it's just inaccurate advice). – john Dec 05 '22 at 07:13
  • in-class intializers came much later into the language than the member initializer list, hence it is possible to find old and outdated material that says you can only initialize the const member in the member initializer list. New books do not necessarily mention that when they only refer to a newer standard – 463035818_is_not_an_ai Dec 05 '22 at 08:46
  • its a little odd to have this https://stackoverflow.com/questions/14495536/how-to-initialize-const-member-variable-in-a-class as dupe, because it also says one needs to use the member initializer list for the const member. – 463035818_is_not_an_ai Dec 05 '22 at 08:48

0 Answers0