Look at this wikipedia article.
There is a pretty nice example with the following memory-efficient pseudo code:
function modular_pow(base, exponent, modulus)
if modulus = 1 then return 0
c := 1
for e_prime = 1 to exponent
c := (c * base) mod modulus
return c
There is even a example for beeing memory-efficient and using less operations. I think getting the c++ code out of it should be possible.
If you use this method, long long
for your solution should be fine.
Not tested but a simple 1:1 translation from the pseudo code from above...
long long result = 1;
int i;
for( i=0; i<d;i++){
result = (result * h) % n;
}