Search code examples
c++implicit-conversioninitializer-list

Why is my value converted from int to char?


#include<iostream>
#include<string>

class Person_t{
private:
        uint8_t age;
public:
        void introduce_myself(){
                std::cout << "I am  " << age << " yo" << std::endl;
        }

        Person_t()
                : age{99}
        { };

};

int main(){
        Person_t person1{};
        person1.introduce_myself();
}

When the shown code is executed, the integer from the initializer list gets converted to a c. I have no explaination why, could someone please explain this to me?


Solution

  • << age
    

    age is a uint8_t, which is an alias for an underlying native type of a unsigned char. Your C++ library implements std::ostream's << overload for an unsigned char as a formatting operation for a single, lonely, character.

    Simply cast it to an int.

    << static_cast<int>(age)