
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can main Be Overloaded in C++
In C++, we can use the function overloading. Now the question comes in our mind, that, can we overload the main() function also?
Let us see one program to get the idea.
Example
#include <iostream> using namespace std; int main(int x) { cout << "Value of x: " << x << "\n"; return 0; } int main(char *y) { cout << "Value of string y: " << y << "\n"; return 0; } int main(int x, int y) { cout << "Value of x and y: " << x << ", " << y << "\n"; return 0; } int main() { main(10); main("Hello"); main(15, 25); }
Output
This will generate some errors. It will say there are some conflict in declaration of main() function
To overcome the main() function, we can use them as class member. The main is not a restricted keyword like C in C++.
Example
#include <iostream> using namespace std; class my_class { public: int main(int x) { cout << "Value of x: " << x << "\n"; return 0; } int main(char *y) { cout << "Value of string y: " << y << "\n"; return 0; } int main(int x, int y) { cout << "Value of x and y: " << x << ", " << y << "\n"; return 0; } }; int main() { my_class obj; obj.main(10); obj.main("Hello"); obj.main(15, 25); }
Output
Value of x: 10 Value of string y: Hello Value of x and y: 15, 25
Advertisements