assignment constructor for const member

Hi all, is there a good way to define a assignment constructor for const members? Below code doesnot compile for function Foo& operator=(const Foo &f),

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
using namespace std;

class Foo {
private:
  const int m_val;

public:
  Foo(int n=0): m_val(n) {}
  ~Foo() {}

  Foo(const Foo &f): m_val(f.m_val) {}

  // does not compile
  Foo& operator=(const Foo &f): m_val(f.m_val) {
    if(this==&f)
      return *this;

    //    m_val = f.m_val;

    return *this;
  }

  int GetVal() const { return m_val; }

};

int main()
{

  Foo f(10);

  Foo g(f);

  cout << g.GetVal() << endl;

  return 0;
}
closed account (zb0S216C)
Initialization lists cannot be used on anything other than constructors and arrays (the version for arrays is different syntactically). Once the constant member is assigned a value, it's value remains constant.

Wazzak
Last edited on
A const member simply cannot be assigned to, and non-static const member makes the entire class non-assignable*

1
2
3
4
5
6
7
const int ans = 42;
const int n = 77;
ans = n; // does not compile

Foo f1(42); // Foo holds a const int m_val inside
Foo f2(77);
f1 = f2; // why do you expect this to compile? 


* technically, you could write a copy-assignment operator that doesn't attempt to modify m_val and that will compile, but after such a = b; a and b will not be equal, and that's rarely acceptable.
Thanks for your replies. It's helpful!
Topic archived. No new replies allowed.