Hi,
here's a fictional example based on a real-world problem I had. Basically, I had a class with a data member who's value couldn't be greater than 9, and I was wondering what type I should have used in the class interface to represent this number.
Ex.1: using unsigned char in the class interface to represent a number in the range [0, 9]
Code:
#include <iostream>
class SmallInteger
{
public:
unsigned char getValue() const
{
return value_;
}
void setValue(unsigned char v)
{
if (v <= 9)
value_ = v;
}
private:
unsigned char value_;
};
int main()
{
SmallInteger s;
s.setValue(7);
std::cout << s.getValue() << '\n'; // Incorrect: user gets a "beep" instead of "7"... at least on my system...
std::cout << static_cast<unsigned int>(s.getValue()) << '\n'; // Correct... but painful
return 0;
}
Ex.2: using unsigned int in the class interface to represent a number in the range [0, 9]
Code:
#include <iostream>
class SmallInteger
{
public:
unsigned int getValue() const
{
return value_;
}
void setValue(unsigned int v)
{
if (v <= 9)
value_ = static_cast<unsigned char>(v);
}
private:
unsigned char value_;
};
int main()
{
SmallInteger s;
s.setValue(7);
std::cout << s.getValue() << '\n'; // Correct!
return 0;
}
I used unsigned int instead of unsigned char because it made the interface more "natural" and easier to use. But then, is there any disadvantage of doing so ? And what about unsigned short ?
Should I (in most case) stick to the "int" type in my interfaces even if the number manipulated can fit inside an unsigned short or an unsigned char AND the user is aware of the constraint ? And performance-wise, is there one way better than the other ?
Thanks.