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 :
{
private:
int x ; // these are private
char y; // data members of the class
public:
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 :
{
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 testObject
return 0 ;
}
In the above code snippet, the statement
Similarly, the statement
This breaks-down the data hiding and encapsulation features of a class and defeats the purpose of Object OrientedProgramming 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.
No comments:
Post a Comment