Passing objects by reference using const

My question is about passing objects to functions by reference. It seems like a function such as save() in my simple example below should be passed an object by reference to avoid the overhead of copying the object, and it should also be passed using const as we don't want or need save() to modify the object. This works fine when the variable x is public, but in the example below where x is private and accessor functions are used, it doesn't.

So, my question is how do you pass objects using const when the class has accessor functions? I tried making save() a friend of MyClass, which worked as save() can now directly access x, but even when save() is a friend it cannot use get_x() to access x. Is there another way to do this so that save() can access x via get_x()?


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
  #include <iostream>
#include <fstream>
using namespace std;

class MyClass
{
	private:
	int x;
	public:
	void set_x(int a) { x = a; }
	int get_x() { return x; }
	//friend void save(const MyClass &ob);
};

void save(const MyClass& ob);

int main() {
	MyClass ob;
	ob.set_x(89);
	save(ob);
	return 0;
}

void save(const MyClass& ob)
{
	ofstream myfile;
	myfile.open("testfile2.txt");
	myfile << ob.get_x();
	//myfile << ob.x;
	myfile.close();
}

You can make the get function const:

int get_x() const { return x; }

now it works with const MyClass& ob
Great, thanks. I knew there must be a way!
Topic archived. No new replies allowed.