3
#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?

bjoekeldude
  • 338
  • 3
  • 11
  • On your system `std::uint8_t` is probably `typedef`d to `unsigned char` see https://en.cppreference.com/w/cpp/types/integer _"...std::uint8_t may be unsigned char..."_ – Richard Critten Oct 09 '22 at 15:52
  • 1
    `uint8_t` is a typedef (a type alias) to some `char` type. As a somewhat common workaround you can use unary `+age` to convert `age` from a `uint8_t` to an `int` on the fly. – Eljay Oct 09 '22 at 15:52
  • Add a `static_cast` when printing. – Jesper Juhl Oct 09 '22 at 16:02

1 Answers1

2
<< 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)
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148