0

I have read from another post that c++11 provides closure functionality. To my understanding, closure is very similar to an object which has a private member and a public method. If not, how is it different then?

kandhan
  • 523
  • 3
  • 9
  • 1
    Look at http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – Bhojendra Rauniyar Dec 07 '15 at 08:26
  • **IMHO**, closure works very similar to function. It has much less common with classes. Classes describe data and behavior, closures describe actions. – Yeldar Kurmangaliyev Dec 07 '15 at 08:27
  • Languages such as Java,C provide the ability to declare methods private, meaning that they can only be called by other methods in the same class. I understand it is done using closures. Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures – kandhan Dec 07 '15 at 11:21

2 Answers2

1

A closure is a function or method which accesses references/pointers from an outer scope.

This is a sample JavaScript closure:

var a = "hello world";

function doStuff() {
   console.log(a); // "a" variable from the outer scope
}

In C++ and every other programming language in the world, a closure refers to the same concept.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
1

A closure is a potentially stateful, callable object. Conceptually, it is a function plus an "environment" of state that's external to the function.

An ordinary function is stateless in the sense that every reference to the function is as good as any other reference to the function; nothing distinguishes a function apart from its name. By contrast, a closure object may (possibly) be copied, and the two copies are distinct and one cannot be substituted for the other.

In programming languages in which functions are legitimate "variable types" or "objects" (like many functional languages), the distinction between functions and closures is much blurrier, since (depending on the language) functions in that context may always be considered to carry around their "environment".

In C++, however, callable object types have a very clear definition as being user-defined types with an overloadeded function call operator, and the new lambda expressions that C++11 adds are just a convenient mechanism for defining such types on the fly and creating a suitable instance.

Here's an example of a callable type:

struct Foo
{
    Foo(int & acc) : acc_(acc), n_(0) {}

    int n_;
    int & acc_;

    void operator()(char c)
    {
        n_ += std::is_digit(c) ? 1 : 2;
        acc += n_;
    }
};

The state held by an object of this type contains both an internal data member (n_) as well as a reference to something else that was provided at construction time. A possible use could be this:

int bar(const std::string s)
{
    int result = s.size(); 
    std::for_each(s.begin(), s.end(), Foo(result));
    return result;
}

That is, we construct a temporary instance of Foo, whose state now comprises an internal counter starting at 0 and a reference to the external object result, and which can be called like a function taking a single char. This callable object is called for each character in the input string s.

With a lambda expression (in fact, a C++14 lambda expression), we can achieve the same result without defining a class type.

std::for_each(s.begin(), s.end(),
              [&result, n = 0](char c) mutable
              { n += std::is_digit(c) ? 1 : 2; result += n; });

In fact, the effect is exactly identical; the type of the closure is essentially the same as Foo. The capture list of the lambda expression (i.e. everything between the square brackets) determines both the data members that the type has and initializes them. For example, the presence of &result means that the type gets an int & member, and it is bound to the variable result in the enclosing scope.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084