main() function overloading in c++ programming
Wednesday, January 22, 2014
Below this code makes many warning in the compiler.
#include
using namespace std;
int main(int a)
{
cout << a << "\n";
return 0;
}
int main(char *a)
{
cout << a << endl;
return 0;
}
int main(int a, int b)
{
cout << a << " " << b;
return 0;
}
int main()
{
main(3);
main("C++");
main(9, 6);
return 0;
}
But if I use the class in code it will be warning and error free. I can overload the main function shows in bellow code. So, main() function is not reserve function in C++,
#include
using namespace std;
class Test
{
public:
int main(int s)
{
cout << s << "\n";
return 0;
}
int main(char *s)
{
cout << s << endl;
return 0;
}
int main(int s ,int m)
{
cout << s << " " << m;
return 0;
}
};
int main()
{
Test obj;
obj.main(100);
obj.main("I like C and C++ programming");
obj.main(100, 200);
return 0;
}
Output:
100
I like C a
100 200
NB: When i post the code in the blog a unwanted html break "<br />" is displayed in some line, please remove the break to run the code properly
Labels: C++
Example may help you to clear the concept of overloading.
ReplyDelete