class object constructor outside main() vs inside main()

Jan 8, 2012 at 6:09pm
My questions will be more clear with an example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class AreaCalculator
{
public:
	int someInitialSetting;

	AreaCalculator(int initialArgument)
	{
		someInitialSetting = initialArgument *3;
	}

	int Square(int x, int y)
	{
		return x*y;
	}
};

/* Scenario 1: Constructor outside main() */

AreaCalculator *obj = new AreaCalculator(8);

int main()
{
	int a;

	a = obj->Square(4, 7);

	return 0;
}

/* Scenario 2: Constructor inside main() */

int main()
{
	int a;

	AreaCalculator *obj = new AreaCalculator(8);
	a = obj->Square(4,7);

	return 0;
}


How are these two scenarios different? Aside from the fact that one is globally available to other functions because it’s declared outside main().
In scenario 1, the object is created dynamically during runtime.
In scenario 2, is the object created when the code is compiled? If the object is pre-created, then that would make the code run faster. Correct? Naturally, if you don’t know the value of initialArgument, then you have no choice but to create the object dynamically during runtime, but if you already knew the value of initialArgument, or maybe remove the initial settings/values all together, then can you make the code more efficient by pre-creating the object when it’s compiled? Would that be considered “efficient”?
What’re some pros/cons of either style of coding?
Thank you.
Jan 8, 2012 at 6:29pm
The objects are created at runtime in both scenarios. I doubt it will affect performance much.

I would prefer scenario 2 because it avoids global variables.
Last edited on Jan 8, 2012 at 6:34pm
Jan 8, 2012 at 6:35pm
I would prefer the second one too. Just so you know, scenario 1 will construct the object even before main() is hit. This could complicate some debugging scenarios.
Last edited on Jan 8, 2012 at 6:35pm
Jan 8, 2012 at 7:38pm
closed account (DSLq5Di1)
Regarding your scenarios, both objects have been created dynamically during run time, the only difference being scope. Best practice is to limit the scope of your variables to where they are needed (Scenario 2).

You do not need to allocate AreaCalculator dynamically in either of these scenarios. The number of objects created (just one in this case) is known at compile time. The value of the constructor argument does not need to be known at compile time, it will accept any value of type int, for which the size is already known.

Also, see:-
http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap
http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/
Topic archived. No new replies allowed.