1

According to the explanation in C++ primer 5th.

Initiate a string with char array and using = operator. It will actually do below two things:

1: Call constructor which accept a const char * to create a temporary string object.

2: Call copy constructor to initiate the true variable;

chapter 13.1 page 618
string null_book = "9-999-99999-9"; // copy initialization

I made a test. and it seems that when I initiate A object with a cahr array. copy construtor have never been called.

#include <iostream>
int b =5;
using namespace std;
class A
{
public:
    A(const char * ch) :chr(*ch) {cout << "contruct ";};
    A(const A & a) : chr(0) {cout << "copy_construc ";::b = 2;}  ;
    A &operator=(const A & a)  {cout << "assignment"; return *this;};
    char chr;
};

int main() {
    A a = "qweqeasd";
    cout << b;
    cout << a.chr;
    A c = A("wrwsx");
    cout << b;
    cout << c.chr;
}

output:

contruct 5qcontruct 5w
BAKE ZQ
  • 765
  • 6
  • 22

1 Answers1

0

What you have here is called copy-initialization.

A a = "qweqeasd";

If T is a class type and the cv-unqualified version of the type of other is T or a class derived from T, the non-explicit constructors of T are examined and the best match is selected by overload resolution. The constructor is then called to initialize the object.

Here the best match is the constructor A(const char * ch) and that is why the output starts with contruct .

P.W
  • 26,289
  • 6
  • 39
  • 76
  • please stop answering duplicates, especially when they are already mentioned. – Matthieu Brucher Mar 04 '19 at 14:30
  • I answered **after** the post was reopened after being closed as a duplicate. – P.W Mar 04 '19 at 14:34
  • I gave a possible duplicate, and we were discussing duplicates. For an almost gold badge, this is a shame. – Matthieu Brucher Mar 04 '19 at 14:48
  • Well, the goldbadge holder was mistaken, your comment suggested that you were not sure (maybe...). It's still not closed as a dupe after nearly two hours when such things happen within minutes. There is only one close vote on it. Let's not "shame" others. – P.W Mar 04 '19 at 14:55