Search This Blog

Tuesday, May 4, 2010

Chaning const reference to pointer

Recently me and Chetan were puzzled, when we saw some code similar to -


=========**=========**=========Code=========**=========**=========



#include<iostream>

using namespace std;

class ABC {
public:
 ABC() {m_val = 0;}
 void change_state() {m_val ++;}
 ~ABC() {}
private:
 int m_val;
};


void function(const ABC *& p_abc) {
        // p_abc->change_state();     // Not Allowed
        p_abc = NULL;                 // Allowed
}

int main() {

 const ABC* p_abc = new ABC();  // p_abc is not const pointer!!

 // p_abc->change_state();      // Not Allowed
 function(p_abc);

 return 0;
}


=========**=========**=======Code End=======**=========**=========

We could not believe this (majic!!)
We thought this is wrong because p_abc is a const pointer!! - what do you say ;)
We even thought that there is some special compiler option!! which is allowing this to happen :)


The answer is, there is only one way to declare a const pointer is
Let's take example of constant pointer to integer -

int *const cnstPtr = new int();
The other two
const int * cnstObj1 = new int(); // and
int const * cnstObj2 = new int();
are declarations for pointer pointing to constant object! and the pointer itself is not constant!

Once again -
*cnstPtr = 5;       // OK - Object is not constant
cnstPtr = NULL;     // NOT OK - Pointer is constant

*cnstObj1 = 5;      // NOT OK - Object is constant
cnstObj1 = NULL;    // OK - Pointer is not constant
also
*cnstObj2 = 5;      // NOT OK - Object is constant
cnstObj2 = NULL;    // OK - Pointer is not constant

What if you want pointer and object both constant?
Use -

const int *const cnstPtrCnstObj1 = new int(); // or 
int const*const cnstPtrCnstObj2 = new int(); 

In this case -
*cnstPtrCnstObj1 = 5;     // NOT OK - Object is constant
cnstPtrCnstObj1 = NULL    // NOT OK - Pointer is constant

and
*cnstPtrCnstObj2 = 5;     // NOT OK - Object is constant
cnstPtrCnstObj2 = NULL    // NOT OK - Pointer is constant

Thanks to Chetan for showing the problem and then telling the cause :)

No comments:

Post a Comment