Wednesday, 3 December 2014

Possibility to overload main function in C++

Is it possible to overload main function in Cpp?

Yes, it is possible by declaring the main function as the member function in a class.
See the below example
#include <iostream>
using namespace std;
class MyTestClass

{

public:
    int main(int iVal)
    {
        cout << iVal << endl;
        return 0;
    }
    int main(char *pcCh)
    {
        cout << pcCh << endl;
        return 0;
    }
    int main(int iVal ,int iVal2)
    {
        cout << iVal << " " << iVal2 << endl;
        return 0;
    }
};
int main()
{
    MyTestClass obj;
    obj.main (12);
    obj.main ("Testin main function");
    obj.main (30, 300);
    getchar ();
    return 0;
}
See the results:
12

Testin main function

30 300

When we use the main function like below, let us predict the results

#include <iostream>
using namespace std;
  int main(int iVal)
    {
        cout << iVal << endl;
        return 0;
    }
    int main(char *pcCh)
    {
        cout << pcCh << endl;
        return 0;
    }
    int main(int iVal ,int iVal2)
    {
        cout << iVal << " " << iVal2 << endl;
        return 0;
    }
int main()
{
   main (12);
     main ("Testin main function");
     main (30, 300);
    getchar ();
    return 0;
}

The above  program will give us the compilation errors like
1>TestCPP.cpp(35): error C2731: 'main' : function cannot be overloaded

1>          TestCPP.cpp(34) : see declaration of 'main'

1>TestCPP.cpp(40): error C2731: 'main' : function cannot be overloaded

1>          TestCPP.cpp(39) : see declaration of 'main'

1>TestCPP.cpp(46): error C2731: 'main' : function cannot be overloaded

1>          TestCPP.cpp(45) : see declaration of 'main'

========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========


 You may get different errors on different compilers.

No comments: