Reputation: 5300
I studied that during initialization of object, for example
string s = "Hello world";
If RHS is implicitly convertible to LHS type object, then Copy Constructor would be called. But I have a friend who is pretty sure that constructor which takes char
pointer as an argument would be called.But I told him that constructor with char
pointer would be called only in cases as below
string s("Hello world");
Is that correct?
Upvotes: 2
Views: 453
Reputation: 81349
Doing
string s = "Hello world";
is equivalent to
string s( string( "Hello world" ) );
so both the constructor taking char const*
and the copy-constructor are called. However, the standard allows copy-elision where the copy-constructor call is elided (not done).
Upvotes: 7
Reputation: 258608
Yes and no. Both are called.
string s = "Hello world";
This is copy initialization. It calls the conversion constructor and constructs a temporary string
from "Hellow world"
and then uses that temporary with the copy constructor to construct s
. (subject to optimizations)
string s("Hello world");
Is direct initialization and calls the conversion constructor directly, constructing s
from "Hello world"
.
Upvotes: 3