0
votes

Please help to complete this execution of an assignment overloading function.

Here is the instruction:

Assignment operator (=) which will copy the source string into the destination string. Note that size of the destination needs to be adjusted to be the same as the source.

Both addition (+) and assignment (=) operators need to be capable of cascaded operations. This means String3 = String1 + String2, or String1 = String2 = String3 should work.

Here is my .cpp file:

 int MyString::Length()
 {
       int counter(0);

       while(String[counter] != '\0')
       {
            counter ++;
       }
     return (counter);
 }

MyString& MyString::operator=(const MyString& rhs)
{

        if(this != &rhs)
        {

                delete [] String;
                String = new char[rhs.Length()];

             for(int i = 0; i <rhs.Length()+1 ; i++)
            {       
                  String[i] = rhs.String[i];
            }       


        }
        return *this;

}

It is called in the main.cpp file by:

String1=String2=String3;

I feel as though I am missing something.Help!!

3
Think about correctness in the face of exceptions! - dirkgently
What is the specific problem ? - Paul R
You are reserving this->Size chars, you are copying this->counter chars. Shouldn't that be rhs.Size or rhs.counter? - Robᵩ
you also forgot to update those variables - Karoly Horvath
You have 4 questions, that essentially ask the same thing. - Stuart Siegler

3 Answers

3
votes

I suppose String is a char*. Perhaps then, Size, which is the new length, needs to be set to the length of rhs, which is the new string. So it should be rhs.Size, and not perhaps this->Size, which is likely to be the case. Note that the terminating null character should be considered in the char array size as well.

After that you can enter the loop, once again take care of all the characters, and the terminating null character. Given we do not know what counter is and assuming it is the new string length without the null character (hence, + 1 accounting for it), I suppose there aren't any problems with the loop.

4
votes

Check out copy and swap idiom.

One of the problems with your code is that it is not exception safe.
It does not even meet the basic exception guarantee.

If it throws during the new operation your object is left in a state that is completely unusable. If fact in a dangerous state because if the destructor is called during stack unwinding because of the exception you get undefined behavior because the destructor will call delete on String a second time.

All methods on an object should act in three stages:

  1. Do all the work that can throw but without changing the object.
    • So if you do throw the object is left in a good state.
  2. Swap the data you created in (1) with the objects data in an exception safe way.
    • Which is why swap() methods are no-throw
  3. Tidy up and delete.
    • Which can throw because the object is again in a consistent state.

The copy and swap idiom encapsulates these steps rather nicely in an easy to use technique.

1
votes

Before starting assignment operator overloading, lets have a look at operator overloading in C++. In object-oriented programming, operator overloading—less commonly known as operator ad hoc polymorphism—is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading is generally defined by the language, the programmer, or both. Operator overloading is used because it allows the developer to program using notation closer to the target domain and allows user-defined types a similar level of syntactic support as types built into the language. It is common, for example, in scientific computing, where it allows computational representations of mathematical objects to be manipulated with the same syntax as on paper. Object overloading can be emulated using function calls.

Now how we overload assignment operator (=),

After we do this assignment operator overloading, we will then be able to assign two variables of our self-defined datatypes. Lets have a look at the below example:

// Operator overloading in C++
//assignment operator overloading
#include<iostream>
using namespace std;

class Employee
{
private:
int idNum;
double salary;
public:
Employee ( ) {
    idNum = 0, salary = 0.0;
}

void setValues (int a, int b);
void operator= (Employee &emp );

};

void Employee::setValues ( int idN , int sal )
{

salary = sal; idNum = idN;

}

void Employee::operator = (Employee &emp)  // Assignment operator overloading function
{
salary = emp.salary;
}

int main ( )
{

Employee emp1;
emp1.setValues(10,33);
Employee emp2;
emp2 = emp1;        // emp2 is calling object using assignment operator

}

Now lets explain this code for overloading “=” operator, we assigned the values to “idN” and “sal” by using the function “setValues” which is a public member function of the class “Employee”, Now our main point is the overloaded function which is defined as “operator =”. Inside this function we assigned the value of salary into the other variable that of the same class, Such that we could use the assignment operator directly in our main() function. Now as you can see in main(), we have two variables emp1 and emp2 of type Employee and we can use the assignment operator directly in our last line of code, It is all because of assignment operator overloading or operator overloading of operator “ = ”.