const struct methods

Hi,

I have a problem trying to call a method from a struct that was declared as const. This is my struct:

1
2
3
4
5
6
struct Bounds
{
	int min;
	int max;
	bool check(int len);
};


The implementation of the method 'check' does not change the values of 'min' and 'max'. It only reads from these two variables:

1
2
3
4
bool Bounds::check(int len)
{
	return ((len <= max) && (len >= min));
}


Now I have a constant instance of this struct called 'TEST'. I tried to call the method 'check' with it, but it gives me an error:

1
2
3
const Bounds TEST = {3, 14};

bool b = TEST.check(6);


error C2662: 'Bounds::check' : cannot convert 'this' pointer from 'const Bounds' to 'Bounds &'.

My guess is that I have to ensure that the method 'check' does not change the values of 'min' and 'max' in order to use this method on a constant instance. Unfortunately I don't know if this is possible and how it is done.

Could somebody give me a hint?
Thanks a lot for your help.

Xoric
You can only call functions that have been declared as 'const' on a const object:

1
2
3
4
5
6
7
8
9
10
11
12
13
struct Bounds
{
	int min;
	int max;
	// function does not change the member variable
	// so it should be declared const.
	bool check(int len) const; 
};

bool Bounds::check(int len) const // here too
{
	return ((len <= max) && (len >= min));
}
That's exactly what I was looking for. I never used a constant function until today.

Thanks a lot for your quick help, Galik!

Greetings,
Xoric
Topic archived. No new replies allowed.