I'm making a class that displays a message to the user and asks them if they want to return to the start of the program, but the message function is in a separate class from where my main() is located. How do I access the main() function from a different class?
This is an example of the stuff I want to do:
main.cpp file:
int main()
{
Message DisplayMessage;
DisplayMessage.dispMessage();
return 0;
}
Message.cpp file:
void dispMessage(void)
{
cout << "This is my message" << endl;
//now how do I call main again in the main.cpp file?
}
Thanks!
Maybe something like that:
and in the
int main()
:you don't, change the return value of
dispMessage
to an int or similar, from the main you check the return code and do different actions based on that.main
is special, you're not allowed to call it in C++.So the "obvious" thing to do is to move everything to another function:
Now you can call
my_main
from anywhere you like (as long as you declare it first in the translation unit you want to call it from, of course).I'm not sure whether this will really solve your problem, but it's as close as possible to calling
main
again.If you call
my_main
from somewhere else in your program then you won't exactly be "returning to the start", you'll be starting a new run through the code without having finished the old one. Normally to "return to the start" of something you want a loop. But it's up to you. Just don't come crying to us if you recurse so many times that you run out of stack space ;-)In C++ it is illegal for a program to call
main
itself, so the simple answer is you don't. You need to refactor your code, the simplest transformation is to write a loop inmain
, but other alternatives could include factoring the logic out ofmain
into a different function that is declared in a header and that you can call.Assuming that you could change dispMessage(void) to something like bool askForReturnToStart() then you could use that to build a loop within main, f.e.: