My textbook yields different results from the same code entered in my program. This code is to show how objects are created.
Questions:
1. Why does my output indicate three trips to both the constructor and destructor when two were anticipated.
2. Why is the constructor visited BEFORE main() is executed?
Thanks.
// Exercise to create and delete objects using both the stack and Free Store. Also to illustrate program flow.
#include <iostream>
#include <conio.h>
using namespace std;
class Math
{
public:
Math();
~Math();
} Tom ; // optional to list the object.
void main ()
{
cout << "Tom is created on the stack.\n";
Math Tom;
cout << "Math is created on the heap by using the new keyword.\n";
Math * pTestScore = new Math;
cout << "delete pTestScore \n";
delete pTestScore;
cout << "Exiting main(). \n";
It's a standard defined function. Some companies' compilers will allow void, but the standard main is:
int main( int argc, char *argv[] )
You don't have to do anything with argc or argv, but they're there if you want to use them.
It goes back a long way to the unix world when C programs were merely utils strung together with a shell script in assembly line fashion to process files. The utils would do their part and return a 0 or 1 or true/false to indicate success or failure.
@learn2adv, just because the standard says so. It would be a bummer if you wrote a piece of code, sent it to someone and the couldn't compile it due to something silly like this.
I should add to what roberts said that int main() is perfectly good too.
Also, note that although main has return type int, it's okay if it doesn't return anything.