General Program Flow.

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.

Math::Math()
{
cout << "Constructor called.\n";

}

Math::~Math()
{
cout << "Destructor called.\n";
system("pause");
}


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";

system("pause");
}

1
2
3
4
5
6
class Math
{
public:
Math();
~Math();
} Tom ; // optional to list the object. 


This instantiates a global object named Tom.

1
2
3
4
void main ()
{
cout << "Tom is created on the stack.\n";
Math Tom;


This instantiates a local object named Tom.

1
2
cout << "Math is created on the heap by using the new keyword.\n";
Math * pTestScore = new Math;


This instantiates a local object that is an allocated block of memory named pTestScore because new calls constructors and delete calls destructors.


Last edited on
Also, globals are initialized before main is executed.

By the way, you may want to fix a few things:
main() must re int, not void.
conio.h is not a standard header and you're not even using it.
Hamsterman & Roberts:

Why is int needed when main() is not returning anything? You are correct about conio.h, it was a carryover from another program.

Thanks for your input.
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.
Topic archived. No new replies allowed.