A Developer's Diary

Mar 28, 2010

A const Reference and a Reference to const object

A reference serves as an alternative name or alias to an object. We cannot define reference to a reference type, but can make a reference to any other data type. C++ imposes several limitations on references. In particular, C++ does not allow you to change which memory a reference points to. Thus, all references are effectively 'const' references. Like normal constant objects, references must be given a value upon declaration.

What should we use then?

MyString& const ref = obj;
OR
MyString const &ref = obj;



/********************************************************
  A reference Example
 ********************************************************/

#include <iostream>
using namespace std;

class MyString{

public:
MyString(const string& str);
~MyString();
void printString() const;

private:
MyString();
MyString(const MyString&);
string m_str;
};

MyString::MyString(const string& str){
m_str = str;
}

MyString::~MyString(){
}


void MyString::printString() const {
cout << m_str;
cout << endl;
}

int main(){
MyString pStr("P");
MyString qStr("Q");
MyString rStr("R");
MyString sStr("S");


// refStr is a reference to pStr

MyString &refStr = pStr;
refStr.printString();
pStr.printString();

// refStr is assigned value at qStr but reference
// still points to pStr
refStr = qStr;

refStr.printString();
pStr.printString();

qStr =  rStr;
// refStr value remains unchanged
refStr.printString();
pStr.printString();

pStr = sStr;
// refStr being reference to pStr, it's value is changed
// as pStr value is changed

refStr.printString();
pStr.printString();

return 0;
}



In the following example, reference itself is a 'const' and is pointing to the data which is not. The code compiles successfully in Microsoft Visual Studio and refStr value is allowed to change but in GCC, throws the error: `const' qualifiers cannot be applied to `MyString&'

MyString& const refStr = pStr; //


In this case the safest solution is to declare reference to the 'const' value as follows

MyString const &refStr = pStr;
OR
const MyString &refStr = pStr;


The compiler will an error whenever the 'const' value pointed by refStr is changed.

refStr = qStr;
// throws an error if MyString const &refStr = pStr;
//OR
//const MyString &refStr = pStr;

No comments :

Post a Comment