简体   繁体   中英

Why copy constructor and overloaded assignment operator are being called for a single assignment operation?

I am writing a class of String in c++ but I got confused when I saw that overloaded constructor and overloaded assignment operators were being called by a single assignment operation. I am thinking that in b = "Check" line, string is first converted into String object hence overloaded constructor was called, then overloaded assignment operator was called.

String::String(const char* s)
{ 
    cout << "Overloaded Constructor::String\n";

        if (s != NULL)
        {
        size = strlen(s);
        bufferPtr = new char[size+1];
        strcpy(bufferPtr,s);
    }
    else
    {
        bufferPtr = NULL;
        size = 0;

    }

}

String & String::operator=(const String&rhs)
{
    cout << "Operator=::String\n";
   if (this != &rhs) // check same assignment
   { 
       size = rhs.size;
        delete [] bufferPtr;
        if(rhs.size != 0)
        {
            bufferPtr = new char[rhs.size+1];
            strcpy(bufferPtr,rhs.bufferPtr);
        }
        else bufferPtr = NULL;
    }
    return *this;
}

String a = "FName";
String b("LUsama");
b = "Check";
`
Output:
Overloaded Constructor::String
Overloaded Constructor::String
Overloaded Constructor::String
Operator=::String

Well, let's see...

  1. a constructor
  2. b constructor
  3. temporary object constructor (contains "Check" string)
  4. temporary object is assigned to b via operator

Just as the output shows. What confuses you?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM