BestR
BestR

Reputation: 679

What is the difference between those ways to create an object?

I have a class name Type. What is the difference between:

1.

Type t=a;

2.

Type t(a);

Where 'a' is some variable.

And what is the difference between:

3.

Type t;

4.

Type t();

Thank you.

Edit: There are some answers which contradict each other. Someone has a final answer?

Upvotes: 1

Views: 134

Answers (4)

aschepler
aschepler

Reputation: 72271

1)

Type t=a;

is called copy-initialization. Constructors marked explicit are not considered.

2)

Type t(a);

is called direct-initialization. All constructors are considered, both with and without the explicit keyword.

3)

Type t;

is called default-initialization. The default constructor (one with no arguments or with all arguments defaulted) is called.

4)

Type t();

declares a function t that returns a Type. This is called the Most Vexing Parse. (Type t{}; is the same as #3 default-initialization but with a visible empty argument list.)

Upvotes: 2

haccks
haccks

Reputation: 106012

Type t=a; and Type t(a); both are same. Both calls the copy constructor if type is default type. Otherwise it is object initialization by 1 argument constructor.
Type t; calls the default copy constructor while Type t(); is function declaration.

Upvotes: 1

Praetorian
Praetorian

Reputation: 109119

Type t=a;

This is copy initialization (§8.5/15). It requires that Type has a non-explicit constructor taking an argument of whatever type a is, or a type that a is implicitly convertible to.

Type t(a);

This is direct initialization (§8.5/16). t can be constructed from the argument a even if the corresponding constructor is explicit.

Type t;

t will be default initialized (§8.5/12).

Type t();

This is a function declaration for a function named t that returns Type by value (§8.5/11).

Upvotes: 8

quantdev
quantdev

Reputation: 23793

1) Type t=a; // Copy initialization

2) Type t(a); // Copy construction (copy constructor or constructor that takes a parameter that has the same type of a)

and then :

1) Type t; // Default constructor

2) Type t(); // NOT a construction : declaration of a function t that takes nothing and return an object of type Type

Upvotes: 2

Related Questions