+35

Question for C++ users!

What is the difference, if any, between the following? (T stands for any class type.) T t; T t(); T t(u); T t = u; Please use KIS principle (removed last S)

3/20/2017 4:43:39 PM

Ram chandra Giri

5 Answers

New Answer

+16

Top two are default constructors, 3rd is a constructor that takes arguments and the bottom one is a copy constructor

+35

T t; default initialization T t(); function declaration T t(u); direct initialization T t = u; copy initialization Thanks @hdo and @jafca.

+4

1.) T t; create an object t and default constructor called. 2.) T t(); same as above; 3.) T t(u); create object t with passing a parameter u, appropriate constructor will be called. 4.) T t= u; create an object t with copy constructor called and copy constructor copies appropriate data members in object t. Note:- here u should be an object of type class T or the base class of class T if inheritance is used. although many other situations be possible here.

+3

1 and 2 are the same. 3 is constructor with arguments. 4 is copy constructor.

+3

About the 2nd statement, it depends on the context where it's in. If it's in a class declaration or in global context (outside any function or class definitions) then it's function declaration. Otherwise it's a statement that instantiates an object of class T using default constructor.