1

I have written a class in C++ and have defined assignment operator function: cplusplus.com recommends following syntax.

check operator= (const check& obj){*cstr = *(obj.cstr); return *this;}

One another syntax is:

void operator= (const check& obj){*cstr = *(obj.cstr);} # Not returning *this

Would you recommend using first method or the second?

Following is my class:

class check {
private:
    string * cstr;
public:
    int a;
    check (string str) { cstr = new string(str);}
    check (const check& obj) {cstr = obj.cstr;}
    ~check() {cout<<"DES"<<endl; delete cstr; }
    check operator= (const check& obj){*cstr = *(obj.cstr); return *this;}
    void display () { cout<<*cstr<<endl;}
};

int main () {
    check da {"one"};
    check pa {"two"};
    pa = da;
    have (pa);
    return 0;
}
Ashish Paliwal
  • 76
  • 1
  • 1
  • 9
  • 3
    Accepted practice is actually to return a *reference* to the class. See http://stackoverflow.com/questions/9072169/why-should-the-assignment-operator-return-a-reference-to-the-object – Brian Bi Aug 08 '14 at 04:44

1 Answers1

3

The usual way of writing the assignment operator is actually

check &operator= (const check& obj){*cstr = *(obj.cstr); return *this;}

i.e., returning a reference to itself. This matches the semantics of assignment for built-in types. Returning check by value may incur an unnecessary copy if the return value is not used. Returning void means you can't write check1 = check2 = check3;.

By the way, check (const check& obj) {cstr = obj.cstr;} is probably wrong. You'd want your copy constructor to make a deep copy and not just copy a pointer. Moreover, I see no reason you need to use a pointer as a class member. If you just store a plain std::string, you can simply use the compiler-generated copy constructor and copy assignment operators.

T.C.
  • 133,968
  • 17
  • 288
  • 421
  • Actually, the OP should also use the member initialisation form, e.g., `check(const check& obj) : cstr(new string(*obj.cstr)) {}`. Of course, if they followed your advice and just stored the string by value, then that automatically solve itself. – C. K. Young Aug 08 '14 at 04:58