tags:

views:

46

answers:

4

Hello everyone,

There is well known recommendation not to include into class interface method that returns a pointer (or a reference) to private data of the class.

But what do you think about method of a class that sends to another class a pointer to the private data of the first one. For example:

class A  
{  
public:
    void fA(void) {_b.fB(&_var)};  

private:  
    B   _b;   
    int _var;  
};

I think that it is some sort of data hiding damage: the private data define state of their own class, so why should one class delegate changes of its own state to another one? What do you think?

Denis

A: 

It is horrible practice if done indiscriminately. There may be cases when it makes sense to tightly couple objects together this way, but in general it should be avoided.

Ignacio Vazquez-Abrams
+2  A: 

Yes, this is violating encapsulation the same way as exposing your variables as public. Only more tricky, since it is harder to detect.

So usually it should be avoided. There are cases when this might be necessary, and if you can be reasonably sure that the callee will not do nasty things with the exposed internal data, it may be acceptable. Note that in this case, it creates a tight coupling between the two classes, so effectively these become a single component.

Péter Török
A: 

If you violate encapsulation, encapsulation is violated.

Since you are talking abstractly, giving another class access to private data means the classes are coupled and therefore may not model the correct abstraction.

msw
A: 

If another object has a direct reference (pointer) to one of your internal objects, they can modify it without you ever knowing about it.

That means it's no longer private.

This breaks encapsulation.

kyoryu