1

I have to write one new class with members something like

class A
{
    static int i;
    const int j;
    char * str;
    ...
    ...
};

Now I want to write assignment operator for it.

A& A::operator=(const A& rhs)
{
    if(this != rhs)
    {
        delete [] str;
        str = new char[strlen(rhs.str)+1];
        strcpy(str, rhs.str);
    }
    return * this;
}

Is it right? I shall ignore the static and const members(?).

Christian Rau
  • 45,360
  • 10
  • 108
  • 185
ExploringApple
  • 1,348
  • 2
  • 17
  • 30
  • 1
    `str = new char[strlen(rhs.str)+1];` *"Is it right?"* - No, it isn't, `std::string` is. – Christian Rau Oct 04 '12 at 18:44
  • 1
    Might I suggest the [copy-and-swap-idiom](http://stackoverflow.com/a/3279550/201270) for assigment operator for better exception safety? Furthermore: Any pressing reasons to use `char*` instead of `std::string`? If not I would strongly suggest using that instead. If you need the `char*`: Smartpointers are almost always the better option when compared to manual memory management. – Grizzly Oct 04 '12 at 19:01

2 Answers2

9

The assignment operator copies one object into another. Since all objects of the same type share the same static members, there's no reason to copy the static members.

const members are another matter. You can't (well, shouldn't) change them, but if two objects have different values for a const member, it might not be a good idea to copy one object into another; the const member won't have the right value. That's why the compiler doesn't generate a copy assignment operator for classes that have const members. So you first have to be sure that copying such an object makes sense, even with the wrong value for the const members; and then ask yourself why it has const members if they don't affect how it behaves.

References too. (yes, there's an echo in here)

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • "That's why the compiler doesn't generate a copy constructor or a copy assignment operator for classes that have const members." The compiler generates copy constructor in case of members with const attribute. #include using namespace std; class base { public: const int i; public: base():i(10) {std::cout << i << endl;} base& operator=(const base &b) { return *this;} //base(const base& b): i(b.i) {} }; int main() { base b1; base b2 = b1; std::cout << b2.i << endl; } – Sandeep Apr 20 '15 at 00:18
5

Static members don't belong to a single object, so you don't need to copy those.

const members can't be changed, so you really can't do a proper copy. References too.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622