2

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 charpointer would be called only in cases as below

string s("Hello world");

Is that correct?

tez
  • 4,990
  • 12
  • 47
  • 67
  • 2
    Also be aware that if `s` was not defined in the same line, it would use the `std::string::operator=(const char*)` function, and not any constructor at all. – Mooing Duck Oct 22 '12 at 18:43

2 Answers2

7

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).

K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • Had to go to your [conversion constructor](http://stackoverflow.com/questions/10905866/what-are-the-conversion-constructors) to understand everything. So constructor with `constant char pointer` is the conversion constructor here right?Thnx for both the amazing answers. – tez Oct 22 '12 at 19:04
  • 1
    @tez: Yes, the constructor taking a `char const*` is a _conversion constructor_. – K-ballo Oct 22 '12 at 19:09
3

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".

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625