Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ any way place class definition after main() function?

I'm writing a small C++ program and need to keep all the code in a single file. In it, I have a class definition. I would like to put the class definition AFTER the main() function. When attempting to do this, the compiler in visual studio complains as it seems class definitions must come before the main() function.

This there a way that I can place the class definition AFTER the main() function? Perhaps with some sort of macro or precompiler trick? It's fine if the code gets compiled with the class def before main, but in the raw source, I need the class def after main.

int main(){

    someClass object;
    //remainder of code

}


class someClass{

    //class code
}
like image 239
Michael Avatar asked Jan 21 '26 09:01

Michael


1 Answers

This will work but it is truly horrible. If I could downvote my own answer, I would. Please don't do this in production.

Assume the file is test.cc

#if defined(guard)
int main(){
    someClass object;
}
#endif

#if !defined(guard)
class someClass
{

};
#define guard
#include "test.cc"
#endif
like image 60
Bathsheba Avatar answered Jan 26 '26 15:01

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!