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;
MyString const &ref = obj;

  A reference Example

#include <iostream>
using namespace std;

class MyString{

MyString(const string& str);
void printString() const;

MyString(const MyString&);
string m_str;

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


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 is assigned value at qStr but reference
// still points to pStr
refStr = qStr;


qStr =  rStr;
// refStr value remains unchanged

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


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;
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;
//const MyString &refStr = pStr;

No comments :

Post a Comment