How many ways are there to initialize a variable?
Here the variable type is initialised using the default ctor MyType::MyType();
This looks like a variable declaration, but it's a function declaration for a function type that takes no parameters and returns a MyType.
This is direct initialization. The variable type is initialized using MyType::MyType(u);
This is copy initialization and the variable type is always initialized using MyType's copy ctor. Even though there is an '=' sign, this is a copy initialization and not an assignment.
The form MyType type(u) should be preferred. It always works where 'MyType type = u' works and has other advantages e.g (It can take multiple parameters)
Output:
$ ./a.exe
Calling Constructor 1
Name is = pankaj
Age is = 10
Calling Constructor 3
Name is = pankaj
Age is = 10
Calling Constructor 2
Calling Constructor 3
Name is = Anky
Age is = 50
Here, MyType a = b; also calls the Constructor 3
Output:
$ ./a.exe
Calling Constructor 1
Name is = pankaj
Age is = 10
Calling Constructor 2
Name is = Anky
Age is = 50
Here MyType a = b; works even when Constructor 3 is commented out because a default copy constructor is created for you when you don't specify one yourself. In such case, the default copy constructor will simply do a
bitwise copy for primitives (including pointers) and for objects types call their copy constructor. If in the later case, a copy constructor is not explicitly defined then, in turn, a default copy constructor will be implicitly created.
1 comment :
A definition specifies a variable's type and identifier. A definition may also provide an initial value for the object. An object defined with a specified first value is spoken of as initialized. C++ supports two forms of variable initialization: copy-initialization and direct-initialization. The copy-initialization syntax uses the equal (=) symbol; direct-initialization places the initializer in parentheses:
int ival(1024); // direct-initialization
int ival = 1024; // copy-initialization
In both cases, ival is initialized to 1024.
Post a Comment