c++copy-constructorassignment-operatorrule-of-three

Do you always have to define a copy assignment operator when a copy constructor is defined?


I've had it drilled into my head many many times that if a copy-constructor is provided, an assignment operator must also be provided. However, there are times when a class can use a copy-constructor but not an assignment operator.

For example:

class A {
public:
  const int myVar;

  A(const int var) : myVar(var) {};
  A(const A& other) : myVar(other.myVar) {};
};

So is this a terrible thing to do? Does the assignment operator need to be defined but made private? Is such a class still copy-constructable?


Solution

  • So is this a terrible thing to do?
    No, it is not.
    Not all classes need to be copy constructible as well as assignable. It is perfectly valid to have copy constructible yet non assignable classes.

    Is such a class still copy-constructable?
    Yes it is.
    As long as your class provides a public copy constructor, Your class is copy constructible.

    Does the assignment operator need to be defined but made private?
    It depends on your usage.
    If your class needs to be assignable then it should ideally not have a const member.

    The default compiler generated copy assignment operator will not work if your class has an const member because it tries to assign to a const member which is not allowed. So if your code needs a copy assignment operator you will have to provide your own overloaded version. But, Anyway this overloaded version cannot provide expected assignment semantics.

    If your class objects do not need to be Assignable then do not define it. If your code does accidentally uses it the compiler will generate an error anyways.