user2991252
user2991252

Reputation: 788

Why the converting-constructor is called here

I am trying to learn about when and where the constructors are called in the code.

I made my own, simple though, stringclass that has these possibilities:

 String string1("hello world");


 string1 = "Hello march!!!";

Concerning the latter one, these two constructors where called in the String-class Called in order...

 converting-constructor

 copy-constructor

I can understand why the copy-constructor is called not really why the converting-constructor is called?

Here are these two constructors:

converting-constructor

 String::String(const char* ch) : _strPtr(0) {

   _strLen = strlen(ch) + 1;
   _strPtr = new char[_strLen];
   strncpy(_strPtr, ch, _strLen);
   _strPtr[_strLen - 1] = '\0';
   cout << "konverterings-constructor\n";
 }

copy-constructor

 String::String(const String& string) {

   _strLen = strlen(string._strPtr) + 1; // behöver ingen "djup-kopia" av vektorlängden.
   if(string.getString()) {
       _strPtr = new char[_strLen];
       strncpy(_strPtr, string._strPtr, _strLen);
       _strPtr[_strLen - 1] = '\0'; // null-terminering
   } else {
       _strPtr = 0;
   }
   cout << "copy-constructor\n";
}

overloading member-function of assignment-operator

 String String::operator=(const String& string) {

   if (this == &string) { // kontrollera om objektet är lika med sig självt.
       return *this;
   }
   cout << "......\n";
   delete [] getString(); 

   _strLen = strlen(string.getString()) + 1;
   if(string.getString()) {
         _strPtr = new char[getLength()];
        strncpy(_strPtr, string.getString(), _strLen);
        _strPtr[_strLen - 1] = '\0'; // null-terminering
   } else {
       _strPtr = 0;
   }

  return *this;
}

Upvotes: 0

Views: 80

Answers (2)

juanchopanza
juanchopanza

Reputation: 227390

I can understand why the copy-constructor is called not really why the converting-constructor is called?

The converting constructor is called because when you assign, since you don't have an assignment operator that takes const char*, a temporary String is constructed from the RHS using the converting constructor, and used to assign to the LHS.

Note that the copy is down to the fact that your assignment operator returns by value. This is unusual for an assignment operator. Usually these return a reference.

Upvotes: 2

kec
kec

Reputation: 2149

Okay, first the array of const chars (which is the type of the string literal) decays to a pointer to const char. Then the converting ctor is called to construct a String from a const char *. Then copy ctor is called to construct a String in the return from your assignment operator. You should return by non-const reference to be idiomatic.

Upvotes: 0

Related Questions