Gaurav
Gaurav

Reputation: 1600

Clarification regarding reference to pointer

I was trying to pass reference to pointers, mainly two cases:

  1. const int* &ref_var - ref_var being a reference to a pointer to a constant integer.
  2. int *const &ref_var - ref_var being a reference to a constant pointer to an integer.

Now the second case works fine since I cannot modify the pointer itself, but in 1st case I am receiving an error message which I don't think should be there since a non-const pointer variable can be passed as argument to a function with constant pointer as parameter.

code:

#include<iostream>

using std::cout;
using std::endl;

void fun(const int* &ref_var)  //error: invalid initialization of reference of type const int*& from expression of type int*
{
     //BLANK
}

int main()
{
    int x=9;
    int *p=&x;     //ERROR VANISHES IF P IS DECLARED AS POINTER TO CONSTANT INT         
    fun(p);
    return 0; 
}

Where as when the function fun is declared as:

void fun(const int *ptr)
{
     //BLANK
}

It works fine despite the argument passed being non-const pointer to int.

Could you please tell me where am I going wrong.

Upvotes: 3

Views: 67

Answers (1)

Matthieu Brucher
Matthieu Brucher

Reputation: 22023

These are two different types and a pointer to an int is not a pointer to a const int. Yes, a pointer to an int can be cast to a pointer to a const int.

The issue here is that there is an additional indirection level, the reference. So you have a reference to a int*. The target is different that a reference to a const int*.

It's similar than having a char*, getting a pointer to it and trying to pass it to a const char**. It will also fail because the inner types are different.

And yes, it can be annoying. The only option is setting the proper type before getting a reference to it, so p must be a const int*.

Upvotes: 3

Related Questions