Protecting class reference from assignment

Hello, I have a problem on which I cannot seem to find a good solution.

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
39
40
41
class Data
{
public:
	Data(int num) : number(num){}
	int number;
};


class Class
{
public:
	Class(int num);
	Data& readonly();

private:
	Data* data;
};

Class::Class(int num)
{
	data = new Data(num);
}

Data& Class::readonly()
{
	return *data;
}


int main()
{
	Class test(5);

	//5
	std::cout << test.readonly().number << std::endl;

	test.readonly() = Data(12);

	//12
	std::cout << test.readonly().number << std::endl;
}


I am trying to build a getter construction for my class that returns a reference of its data, so that it won't copy the data on calling. The code above is an example of my setup. The key problem is that the returned reference may not be assigned to something else, like I do in the main(), because in my actual code, things go horribly wrong internally in the Class class when the reference gets changed from the outside.

I have tried changing the returned data reference to be const, but this disallows me from calling any functions on it aswell as getting the variables of the data class.

Am I missing something here that could make this work? Or is there a better way to get a reference of the private data without it being overwritten like that.

Kind regards,
Morgaza
Define these member functions that you are going to call for an object Data also as const.
There are three approaches. The first one is to return const reference. otherwise it is not clear why you named the getter as readonly.

const Data& readonly();

The second one is to return a copy of the object

Data readonly();

And the third is to define the copy assignmnet operator as deleted.

Data & operator =( const Data & ) = delete;



Last edited on
Hello Vlad, thanks a lot for your answer, it made me realize that I was doing something propperly wrong. In my original code I overloaded the assignment operator to make a copy of a class. This was why I thought I was overwriting the reference, but in fact I was actually copying the variables of class righthandside into class lefthandside. So instead I will take out the critical parts of the assignment operator and only copy the variables that are allowed to be copied (Such as int number).

Data & operator =( const Data & ) = delete;

This solution really seems interesting to me however, but I cannot seem to get this syntax to work in Visual Studio. Is that because it is pseudocode?

Kind regards,
Morgaza
Last edited on
In MS VS you can declare the copy assignment operator as private and do not provide its definition.
Topic archived. No new replies allowed.