Hi,

I am a new user. I was wondering if there is a way to have a alias to a pointer such that the alias is read only (I mean not the the variable it points to is not modifiable)

I have explained with an example (code is given below for reference)

suppose v1 is an int variable, and ptr1 is a pointer to v1.

suppose the alias to ptr1 is ptr2.

I want an alias to ptr1, in such a way that the alias doesn't modify the variable v1.

When ptr1 points to v2, the alias also must point to v2, but should not be able to modify v2.

I tried doing it, but the alias that I thought I created, isn't alias to ptr1 in the first place.

Question
---------
a) Is this possible, if so how is it achievable ?
b) In my example, why is ptr2 having a different address from that of ptr1, am I missing something ?

Let me know if you need more information.

Thanks,
Muthu

#include <iostream>
using namespace std;


int main()
{
    system("clear");

    int v1 = 10, v2 = 20; 


    cout << "&v1   = " << &v1 << "\t\tv1   = " << v1 << endl; 
    cout << "&v2   = " << &v2 << "\t\tv2   = " << v2 << endl; 

    cout << "\n\n------------\n\n";

    int* ptr1 = &v1;
        
    const int* const & ptr2 = ptr1;
        
    cout << "&ptr1 = " << &ptr1 << "\t\tptr1 = " << ptr1 << "\t*ptr1 = " << *ptr1 << endl;
    cout << "&ptr2 = " << &ptr2 << "\t\tptr2 = " << ptr2 << "\t*ptr2 = " << *ptr2 << endl;


    cout << "\n\n------------\n\n";
        
    ptr1 = &v2;

    cout << "&ptr1 = " << &ptr1 << "\t\tptr1 = " << ptr1 << "\t*ptr1 = " << *ptr1 << endl;
    cout << "&ptr2 = " << &ptr2 << "\t\tptr2 = " << ptr2 << "\t*ptr2 = " << *ptr2 << endl;

    return(0);
}

since ptr2 is a reference to ptr1, when you change ptr1 the change is also reflected in ptr2. What you can't do with ptr2 is assign a new value to it like *ptr2 = 2; is an illegal statement because ptr2 is a const.

This article has been dead for over six months. Start a new discussion instead.