Can a const function accept member parameters ad reference?

closed account (Ey80oG1T)
Can I do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class foo
{
public:
  void bar()
  {
    baz(num, 6);
  }

private:
  void baz(int& val1, int val2) const
  {
    val1 = val2;
  }

private:
  int num;
};


Notice how the const function does modify a member variables. Is that okay?
Last edited on
It compiles and runs OK as baz() doesn't directly modify the member variable.

Try it with a compiler.

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
class fooy
{
public:
	void bar()
	{
		baz(num, 6);
	}

	int get() const {
		return num;
	}

private:
	void baz(int& val1, int val2) const
	{
		val1 = val2;
	}

private:
	int num;
};

int main()
{
	fooy fo;

	fo.bar();

	std::cout << fo.get() << std::endl;
}


Its bar() that actually changes num, which isn't const so OK. If bar() was const, then there is a problem.
Last edited on
closed account (Ey80oG1T)
Oh okay, so is it recommended?
Topic archived. No new replies allowed.