TheVTM
TheVTM

Reputation: 1590

Initialization Lists in Const Fields dont generate operator=

For some reason , the compiler cannot generate the operator= for this class because of the initialization of the const field _constFoo, I just wanna know why. Using VS2010.

class Foo {
public:
    Foo(int f) : _constFoo(f) { }
    int getFoo() const { return _constFoo; }
    //void operator=(const Foo &f) { memcpy(this, &f, sizeof(Foo)); }
private:
    const int _constFoo;
};

int main(int argc, char *argv[])
{
    Foo f(5);
    cout << f.getFoo() << endl;
    f = Foo(6); //error C2582: 'operator =' function is unavailable in 'Foo'
    cout << f.getFoo() << endl;
}

Upvotes: 0

Views: 147

Answers (2)

Luchian Grigore
Luchian Grigore

Reputation: 258618

The standard disallows it:

C++03 12.8. Copying objects

12) [...] A program is ill-formed if the class for which a copy assignment operator is implicitly defined has:

  • a non-static data member of const type, or
  • a non-static data member of reference type, or
  • a non-static data member of class type (or array thereof) with an inaccessible copy assignment operator, or
  • a base class with an inaccessible copy assignment operator.

[...]

emphasis mine.

So your program is ill-formed. By not defining your own assignment operator, the compiler attempts to implicitly define one.

Upvotes: 2

Christian Stieber
Christian Stieber

Reputation: 12496

That's because the default assignment operator, which just copies the data, can't be used on "const". Thus, the object can't just be blindly copied.

Upvotes: 0

Related Questions