felknight
felknight

Reputation: 1423

How to cast a variable member to pass it as reference argument of a function

When I try to compile some code very similar to this one with VC++2015 I get a:

C2664 cannot convert parameter number 1 from 'unsigned int' to 'short &'

class Foo
{
public:
    unsigned int A;
    unsigned int B;
}

void foo(short& a)
{
    a++;
}

void main()
{
    Foo f;
    foo(f.A);
}

What is the correct way to cast it?

Upvotes: 1

Views: 210

Answers (1)

M.M
M.M

Reputation: 141554

It is not possible to do this with a cast because unsigned int cannot be aliased as short. To call this foo without changing it, the code would be:

if ( f.A > SHRT_MAX )
    throw std::runtime_error("existing value out of range for short");

short sh = f.A;
foo(sh);
f.A = sh;

You may want to check sh >= 0 before reassigning it to f.A; and foo should guard against integer overflow.

Upvotes: 1

Related Questions