The following article discusses the dangers of returning a reference to private data of a class.
First, it is shown how a reference to private data member is returned from a member function and then the consequences of doing so are discussed.
Returning a Reference to Private Data in a Class :
The example below shows how a reference is returned to a private data member in a class :
class ATestClass { private: int x ; // these are private char y; // data members of the classpublic: AtestClass () // default constructor of class { -------------------------------- ---body of constructor---- -------------------------------- } int &retReference() // this is the bad function that returns reference to private member x { x = 10; return x ; // dangerous !! (reference to private data x is returned) } };
The catch in the above code snippet is that the function retReference() can be used as an lvalue in any assignment statement. The code snippet below shows how :
int main() { ATestClass testObject; // creates an object of ATestClass testObject.retReference() ; // sets the value of x in testObject as 10 int z = testObject.retReference() ; // z becomes 10 testObject.retReference() = 20 ; // dangerous !! the private data member of ATestClass is directly accessed and modified ! int &a = testObject.retReference() ; //again dangerous !! a becomes a reference to private data x in object testObject a = 100 ; // dangerous !! private data member x in object testObjectreturn 0 ; }
In the above code snippet, the statement
testObject.retReference() = 20 ;
is a perfectly valid C++ statement because the function retReference() returns a reference to int x, and hence it can be used as an lvalue in any assignment statement. Thus, even if data member x is private in class ATestClass, it is directly accessed through object testObject and is modified.
Similarly, the statement
int &a = testObject.retReference();
declares a as a reference to private data member x in testObject. Then, the following statement
a = 100 ;
uses a as an alias (reference) to private data x and modifies its value.
This breaks-down the data hiding and encapsulation features of a class and defeats the purpose of Object Oriented Programming in the following ways :
- The private data in the class no longer remain “private” as they can be directly accessed through any variable that is a reference to the private data.
- The encapsulation feature is also destroyed as data and its functions are no longer bound together. Data can be accessed without the help of the member functions of the class.
Thus, we have seen how a simple thing such as returning references to private data members of a class destroy Object Oriented Programming concepts. This is an example of a poor programming practice, and should be avoided.