Denis
Denis

Reputation: 21

Is it a good object-oriented-design practice to send a pointer to private data to another class?

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

Upvotes: 2

Views: 157

Answers (4)

kyoryu
kyoryu

Reputation: 13055

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.

Upvotes: 1

msw
msw

Reputation: 43487

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.

Upvotes: 0

Péter Török
Péter Török

Reputation: 116266

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.

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798546

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.

Upvotes: 0

Related Questions