vendredi 8 octobre 2021

Relation between static constant member variables and narrowing conversions in C++

Coding in C++20, using a GCC compiler.

Based on the code shown below, the program will raise a narrowing conversion error/warning due to the int to char implicit conversion. However, if I add static const/constexpr to the int var {92}; line, the program runs without raising any errors/warnings.

  1. Why does this happen?
  2. When should I be using static const/constexpr member variables?
  3. Why are constexpr member variables not allowed?
#include <iostream>

class Foo {
    private:
        int var {92};
    public:
        void bar() {
            char chr {var};
            std::cout << chr << '\n';
        }
};

int main() {
    Foo foo;
    foo.bar();
} 

Aucun commentaire:

Enregistrer un commentaire