What is object closure explain with example in c++?
Answers
Answer: A closure is basically a function B nested inside a function A that can access A's local variables.
Explanation:
Example:
function A() {
var x = 5;
function B() {
print(x);
}
return B;
}
If you come from a C++ background, this is rather hard to digest. When we try to call the function returned by A, Won't that x be invalid since A() terminated?
The answer is that x actually lives on. That B we returned actually carries x around with it implicitly.
In a more general sense, a closure is a function bound to some data. In a language without closures like C, every program has a fixed number of functions. With closures, you can, in a sense, "create functions" by binding them to dynamic data. Of course, nobody's stopping you from emulating closures in C, but it can be a pain sometimes.
A function object consists of two things. The first thing is the code for the function, the second is the scope in which it executes. In a closure, the scope in which the function executes and the code are detached from each other. The same code can execute in a variety of scopes.
If this were allowed in a completely unrestricted way it would result in great confusion. Even when it's something as loose as dynamic scoping (the function inherits the scope of the place where it was called from) it becomes very confusing.
#SPJ3