- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Functions that can’t be overloaded in C++
- Operators that cannot be overloaded in C++
- Functions that cannot be overloaded in C++
- What are the different ways for a method to be overloaded in C#?
- What are overloaded indexers in C#?
- Overloaded method and ambiguity in C#
- Can main function call itself in C++?
- Hiding of all overloaded methods in base class in C++
- Difference between void main and int main in C/C++
- Difference between “int main()” and “int main(void)” in C/C++?
- Why main() method must be static in java?
- Can we overload Java main method?
- Can we override the main method in java?
- Can we overload the main method in Java?
- Differentiate between int main and int main(void) function in C

Advertisements