0
#include <iostream>
#include <string.h>
using namespace std;

class String 
{
    private:
        enum { SZ=80 }; 
        char str[SZ]; 
    public:
        String(){
            strcpy(str, "");
        }
        String (const char s[]){
            strcpy(str,s);
        }
        String operator = (String obj){
            String newObj;
            strcpy(newObj.str,obj.str);
            return newObj;
        }
        void display(){
            cout << str;
        }

};
int main()
{
    String s1("ABC"); 
    String s3;
    s3 = s1;
    s3.display();
return 0;
}

I'm trying to copy one Char string Object to second one using the above code (assignment operator) operator=, Why it's not working? I tried my best but still failed.

Asif Mushtaq
  • 3,658
  • 4
  • 44
  • 80

1 Answers1

0

Your assignment operator is not assigning to the String itself, but to a temporary var. This would be the correct way to do it:

String& operator = (const String& obj) {
   strcpy(str, obj.str);  // in this line, obj is copied to THIS object
   return *this;          // and a reference to THIS object is returned
}

The assignment operator always has to change the object itself, to which something shall be assigned. Typically also a reference to the object itself is returned.

There are some other problems in your code:

strcpy() should not be used, because it has no range check (size of buffer) and though is unsafe.

And when using strings as a parameter (or any bigger objects like classes with a lot of members, vectors etc), you should use const references like in my example (the "const" and "&"). This is safer (because you can not accidently change the content of the parameter) and MUCH faster, since only a (very small) reference has to be copied, and not the whole content of the parameter.

user2328447
  • 1,807
  • 1
  • 21
  • 27