c++classconstantscopy-assignmentmove-assignment-operator

Explicitly defaulted copy/move assignment operators implicitly deleted because field has no copy/move operators. C++


I'm new to C++ and dont know why this is happening and how to fix it. Here's some snippets of the code:

header file:

class Dictionary{

    private:
        string filename;       
        const string theSeparators;   

    public:
        Dictionary(const string& filename, const string& separators = "\t\n");

        Dictionary() = delete;   

        ~Dictionary() = default; 

        Dictionary(const Dictionary&) = default; 

        Dictionary(Dictionary&&) = default;  

        Dictionary& operator=(const Dictionary&) = default; 
    
        Dictionary& operator=(Dictionary&&) = default;   
};

cpp file:

Dictionary::Dictionary(const string& filename, const string& separators = "\t\n"){

/* some stuff for the filename*/
}

error: copy assignment operator of 'Dictionary' is implicitly deleted because field 'theSeparators' has no copy assignment operator

   const string theSeparators;

error:move assignment operator of 'Dictionary' is implicitly deleted because field 'theSeparators' has no move assignment operator

   const string theSeparators;   

Solution

  • This data member

     const string theSeparators; 
    

    is defined with the qualifier const. So it can not be reassigned after its initialization in a constructor.

    Thus the compiler defined the copy and move assignment operators as deleted.

    You can just remove the qualifier const for this data member.

    Or if to keep the qualifier const for the data member then you have to use mem-initialing lists in constructors like for example

    Dictionary::Dictionary(const string& filename, const string& separators = "\t\n")
        : filename( filename ), theSeparators( separators )
    {
        //...
    }
    

    But in this case the copy and move assignment operators will be still deleted.