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.
VS2010

class A
{
public:
	A():x(0){}
	A(int x): x(x){}
	const int x;
};
class CMyClass
{
	A m_A;
};

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;
}
commented: Thank you. Clear explanation. +3

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 {
  private:
    int x;
    double y;
    some_class z;
  public:

    //The default assignment operator would look like this:
    A& operator=(const A& rhs) {
      //first, assign base-classes:
      B::operator=(rhs);
      C::operator=(rhs);
      // 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).

commented: Thorough. I see now. Thank you. +3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.