Default construtor

Hi,
Is there any difference between the 2 creation objects in the main() ?
I mean what does the compiler do with those 2 options, do they have the same assembly code ?
Another Q is - if i'm adding an explicit definition to the class like : CDefaultConstructor() { cout<<"Create"; } would it makes any difference ?


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
#include <iostream>

using namespace std;

class CDefaultConstructor
{

public:

	void sample() { cout<<"Printing - CDefaultConstructor::sample\n"; }

private:

	int	mX;

};

int main()
{
	
	CDefaultConstructor	ex_1_defConstructor;
	ex_1_defConstructor.sample();

	CDefaultConstructor	ex_2_defConstructor = CDefaultConstructor();
	ex_2_defConstructor.sample();
}



Thanks
User
Last edited on
Is there any difference between the 2 creation objects in the main() ?

Yes, the two examples are different.
In the first example, the compiler allocates space for mX and provides a default constructor which does nothing.

In the second example, a temporary instance of CDefaultConstructor is pushed on the stack, its default constructor called (again provided by the compiler and does nothing). The temporay instance is then copied to ex_2_defConstructor using a compiler provided copy constructor.

do they have the same assembly code ?

No.

if i'm adding an explicit definition to the class like : CDefaultConstructor() { cout<<"Create"; } would it makes any difference ?

In what way?
In the first example, "Create" would be displayed once.
In the second example, "Create" would still only be displayed once, since ex_2_defConstructor would be constructed by the compiler provided copy constructor.


The both can have the same assembler code due to optimization which results in omitting of the copy constructor.
> Is there any difference between the 2 creation objects in the main() ?

Yes.

CDefaultConstructor ex_1_defConstructor; does not require an accessible copy constructor.

CDefaultConstructor ex_2_defConstructor = CDefaultConstructor(); does.
(Even though the copy would be elided).

http://liveworkspace.org/code/2F8bmj$0
@JLBorges
(Even though the copy would be elided).


To make it more clear I would say that the copy constructor will not be used due to optimizaion. But it shall be declared and be accessible that the code could be compiled.
But at the same time in both examples the assembler code can be the same.
Topic archived. No new replies allowed.