Error C2582: function 'operator =' is not available in 'B'

The following code gives a compilation error (at least when using MS VS 2008) for the string "e = f" in main ():

error C2582: function 'operator =' is not available in 'B'

class A { public: A() { } static const double x; }; const double A::x = 0.0; class B { public: B() : x(0.0) { } const double x; }; int main( int argc, char *argv[] ) { A c,d; B e,f; c = d; e = f; return 0; } 

A default assignment operator must be generated for both classes: A and B !?

in 12.8.10: "If the class definition does not explicitly declare the copy assignment operator, one is declared implicitly."

+5
source share
3 answers

An implicitly generated statement recursively assigns each non-static member. However, x is const , so it cannot be assigned. This prevents the creation of an implicit statement (in particular, it defines it as remote).

This is stated in C ++ 11 12.8 / 23:

The default assignment operator for copy / move by default for class X is defined as remote if X has:

  • ...
  • non-static data member of type const non-class (or its array) or
  • ...

(Although I just noticed that your compiler precedes C ++ 11, the rules are similar, but are specified in different languages, in old dialects without the concept of "remote" functions).

If you need an assignment operator for a class whose members (or base classes) cannot be reassigned, you will have to define it yourself.

In class A constant member is static, so it is not part of the object. Therefore, this does not prevent the assignment of an (empty) object.

+14
source
Field

'x' is of type const const double , the assignment operator does not make sense by default and is implicitly deleted here.

+4
source

The obvious difference between classes A and B is a constant that is static or non-static. Assigning a constant variable / should not be possible in any case.

The compiler obviously tries to create a default assignment operator method for class B and silently decides not to generate it, because the member x does not allow assignment.

Took me quite a while to find out ...

BTW: If you ignore the initialization of x in class B, the compiler is smart enough to recognize this error.

+2
source

Source: https://habr.com/ru/post/1201566/


All Articles