0

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!!

Bart
  • 19,692
  • 7
  • 68
  • 77
user1363061
  • 105
  • 1
  • 4
  • 12

3 Answers3

4

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.

Community
  • 1
  • 1
Martin York
  • 257,169
  • 86
  • 333
  • 562
  • the "tidy and delete" shouldnt need to be done because in C++ we're using smart pointers. (You are, right?) – Mooing Duck Apr 28 '12 at 21:56
  • @MooingDuck: Smart pointers are an implementation technique. The principles still hold there is a tidy up and phase. Also String is really a container thus smart pointers don't really apply. Smart pointers and containers are different but parallel techniques that are applied to memory management. – Martin York Apr 29 '12 at 09:13
3

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.

  • so when I say String = new char[Size.Length()] is this what you mean? Or should it be declared like so, Size = rhs.Size; and yes I goofed on the loop but I have edited it. – user1363061 Apr 28 '12 at 22:02
  • After 'delete [] String', this should be done: 'Size = rhs.Size'. After that is done, the new 'String' should be: 'String = new char[rhs.Size]', or just 'String = new char[Size]', since 'Size' is now equal to 'rhs.Size'. If Size disregards the terminating character, add one to it. The point here is that you need to make any member variables equal to the object passed as argument to the assignment operator. –  Apr 28 '12 at 22:07
  • 1
    It's good to know what you got wrong. But in the end you have to use copy and swap (or work out how to write it in an exception safe way). The copy and swap idiom is also only three lines so it is also easier to write once you know it. – Martin York Apr 28 '12 at 22:16
  • Thank you for your help! I've figured it out! :) – user1363061 Apr 28 '12 at 22:18
1

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 “ = ”.