Sunday, August 22, 2010

Nested function in c++

Recently while working on some code, I required to create nested function. Well in most case you can avoid use of nested function but in my case, in one function I required to use same code repeatedly and that piece of code was not going to be used else where so I wanted to keep that code inside original function only and I also wanted to remove redundant code. So I thought to create nested function.

By standard C++ dose not support use of nested function, some compiler allows it but that depends on compiler being used. So there is one work around by using you can achieve nested function in C++.

By using local class and overloading function operator we can simulate nested function. Following is my sample code to achieve nested function.
void foo() {
    class DoMyWork
    {
    public:
        int operator() (int args) {
            qDebug() << "Parameter passed:" << args;
            return args + 5;
        }
    } doMyWork;//creating instance of DoMyWork
//calling simulated nested function
    int retVal = doMyWork(5);
    qDebug() << "Returned value:" << retVal;
}
So that was all, hope this helps.

No comments:

Post a Comment