Any idea why declaring a const int inside a data member of a class would cause error C2582: 'operator =' function is unavailable in 'CMyClass'?

There is a lot going on in CMyClass and I don't know where to start looking for the error. I am using the default operator= . The simplified version below compiles just fine. The real version has hundreds of lines of code, and works without errors (except when the member class declares a const object). So strange.

class A
	A(int x): x(x){}
	const int x;
class CMyClass
	A m_A;
5 Years
Discussion Span
Last Post by mike_2000_17

Because the data member is const the = operator can't change its value. So using the = operator on any objects from this class will cause an error.

Your = operator is defined ~ like so

A& A::operator =(const A & obj)
if (this != &obj)
a = obj.a;//fails here since a is const
return *this;

Edited by gerard4143: n/a

Votes + Comments
Thank you. Clear explanation.

The basic requirement for the default assignment operator to be available for a class is that all the data members and base classes also have an assignment operator available (with the additional exception that data members of reference type also disable the default assignment operator because of the special semantics they have).

So, you can consider, for practical purposes, that the default assignment operator has the following implementation generated by the compiler:

class A : public B, public C {
    int x;
    double y;
    some_class z;

    //The default assignment operator would look like this:
    A& operator=(const A& rhs) {
      //first, assign base-classes:
      // then, assign the data members:
      x = rhs.x;
      y = rhs.y;
      z = rhs.z;

Clearly, the above can only work if all the data members can be assigned a value, and if all base-classes have an assignment operator (default or not).

In your example code, the class A has a const data member which cannot be assigned a value (it is "constant") after initialization (in the initialization list of the constructor). So, the class A does not have a default assignment operator generated for it, and in turn, the class CMyClass will not have a default assignment operator generated for it either since it has a data member which is not assignable (m_A).

Votes + Comments
Thorough. I see now. Thank you.
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.