Direct and Copy Initialization

Can someone please tell me the difference between Direct and Copy
Initialization???

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Object
{
int x;
public:
Object()
{}

Object(int i)
{
x=i;
}
};

int main()
{
Object obj(3);//Direct Initialization
Object obj=3;//Copy Initialization
return 0;
}
Last edited on
There is no Copy Initialization/construction in use here.
Object obj=3; will use Object(int i) constructor - which is the same constructor that Object obj(3); uses.


Copy construction is where a new object is created using an existing object of the same type (either using the compiler default copy constructor or your own supplied copy constructor)

1
2
3
Object obj2(4);
Object obj3(obj2); //copy construct
Object obj4 = obj2; //copy construct 



Other Information
Object(int i) is an example of a converting constructor - it can be used to convert an integer into an Object type - if you dont want the compiler to do this implicitly then you can tag this constructor as explicit)

Last edited on
The OP is correct.

Object obj=3; is copy initialization: http://en.cppreference.com/w/cpp/language/copy_initialization

Object obj(3); is direct initialization: http://en.cppreference.com/w/cpp/language/direct_initialization
Mmm - I will read the link - but I cannot see why the compiler could not optimize
Object obj=3; to direct initialisation.

(Unless it's all a matter of wording - but I will read the links as I say)
In this case there is no difference at all between the two.
Topic archived. No new replies allowed.