norse
norse

Reputation: 3

Does passing lambdas violate encapsulation when they use a private member variable?

I wrote a function to pass to a third party's class. A static function worked fine until the function needed access to a private member variable to do its work. I can do that using a lambda expression (given that it is converted to std::function either automatically or by casting).

Example:

void classA::doingThings()
{
...
    classB::needsHelpToDoAThing(
    [&](std::type foo) -> size_t { return myFunction(foo); }
    );
...
}

size_t class::myFunction(type foo){
...
type someVar = m_somePrivateMember ...(some work)
...
}

But I don't really understand what I'm doing. Now this other class is using private member variables from a different class. Doesn't this violate encapsulation? Is this a hack or am I missing/misunderstanding a concept?

Upvotes: 0

Views: 312

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275270

Encapsulation is the idea that other code doesn't get to poke around in your innards willy-nilly.

Here you created a helper function that can poke around in your innards. This helper function is part of your innards, even if you pass it to someone else.

This no more breaks encapsulation than a member method accessing private data. While it isn't part of the interface of the class explicitly, it is still part of the implementation.

Upvotes: 1

Related Questions