

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Questions & Answers
- Functions that can’t be overloaded in C++
- Operators that cannot be overloaded in C++
- Functions that cannot be overloaded in C++
- Why main() method must be static in java?
- What are the different ways for a method to be overloaded in C#?
- Can main function call itself in C++?
- Can we overload Java main method?
- Can we overload the main method in Java?
- Can we override the main method in java?
- Overloaded method and ambiguity in C#
- What are overloaded indexers in C#?
- Why the main method has to be in a java class?
- Can the main method in Java return a value?
- Can we change the order of public static void main() to static public void main() in Java?
- Can We declare main() method as Non-Static in java?
Advertisements