Jump to content
  • Advertisement
Sign in to follow this  
neverland

question about object initialization

This topic is 4751 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

i wrote code below:
#include <iostream>
using namespace std;
class A {
public:
	A() :i(0) {
		cout << "default constructor called" << endl;
	}
	A(int n) : i(n) {
		cout << "1 argument constructor called" << endl;
	}
	A(const A& obj) : i(obj.i) {
		cout << "copy constructor called" << endl;
	}

private:
	int i;
};
int main()
{
	A a1(10);

	A a2 = A::A(10);

	A a3;
	a3 = A::A(10);
	
	return 0;
}
Somebody says that the second clause in the main function creates a nameless temporary A instance. Then, a2 is initialized from that temporary by the copy constructor. But the output is "1 argument constructor called", it is just like the output of the first clause:just one constructor called and no copy constructor called. so, will somebody tell me what does this clause "A a2 = A::A(10);" actually do , and what is the difference between the three methods in the main function ?

Share this post


Link to post
Share on other sites
Advertisement
When you first create an object, the compiler is allowed to use the initialization, rather than copy or assignment operator.

In other words

A a = A::A(10);
is the same as
A a = A(10);
is the same as
A a = 10;
is the same as
A a(10);

This isn't the case for a3 in your code, where = is used to copy instead.

In other words, =, when used on an object being first created, means "initialization" rather than "copy".


A more interesting question is - what does:
A a(A(10));
do? (I don't know, I'd have to try it and see - my guess is copy).

Share this post


Link to post
Share on other sites
I guess A a(A(10)); will be optimised by the compiler, but it looks like it should create a temporary variable initialized with 10, then copy construct a with this temporary variable.

The easiest way to find out would be to build it and see what happens, but I'm too lazy ;) hehe

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!