Search code examples
c++copy-constructorassignment-operator

is it possible to forbid assignment if there is no explicit copy constructor? c++


Let's assume I have class with no explicit copy constructor. Is it possible to forbid operation of assigning or copying objects for this class? For example:

class A
{
   // data, methods, but no copy constructor and no overloaded assignment operator
};

A object1;
A object2;

object1 = object2; // make compiler error here

A object3 = object1; // or here

Solution

  • You could mark the copy-constructor and copy-assignment operator as deleted:

    class A
    {
    public:
        ...
    
        A(const A&) = delete;
        A& operator=(const A&) = delete;
    };
    

    If your compiler doesn't support C++11 features like this, just make the functions private.