Wednesday, October 19, 2005

Returning Private members

This article is especially in reference with:
http://myspad.blogspot.com/2005/03/return-private-member-variables-of.html
Here, author has code snippet that gives unrestricted access to private member data! Well this is violation! So though a correct way of returning by refrence "&" has been used but still it misses one more important design detail.
Lets try to analyze this whole thing using an example.

class A { int i; };
class B {
A a; int y;
public:
// Note this function declaration
const A& getA() const;
}

The above function getA() completely maintains the semantics and though access to private member has been refrenced, it still does not allow user to modify the contents.

2 Comments:

Blogger Eklavya said...

Consider this piece of code:
#include <iostream>
using namespace std;

class A
{
int a_var;

public:
A(int a0):a_var(a0) {};
const int& get_internals() const
{
return a_var;
}
};

int main()
{
A a_obj(10);
int& a_var_ref = const_cast <int&>(a_obj.get_internals());
int *a_var_ptr = &a_var_ref;
cout << "\n Before changing - " << a_var_ref << endl;
*a_var_ptr = 20;
cout << "\n After changing - " << a_obj.get_internals() << endl;
}

10:09 PM  
Blogger shlok said...

Well .... the idea I guess is not to break OO semantics and still achieve desired result! So when access to a private aggregated object is desired, return by reference for optimization makes perfect sense.
But then again to keep overall OO semantics in place, return type should be made constant! It simply explains the nature of interface, saying the return is supposed to be constant and not to be changed.

From a hacking perspective, breaking things would be anyways possible! How about if you simply make a pointer of A to point to object of A and simply map memory regions? Simple! But to avoid programmer unknowingly doing a mistake, general semantic rules can still be applied resulting in better, cleaner and bug free code!

10:41 AM  

Post a Comment

<< Home