const object

Hi!
Well im writing a program where in every object has a name,latitude and longitude assigned to it and im writing this function to calculate which city is closer to 0,0

bool ClassName::less(ClassName const& passedObj)
{
bool b;
CWaypoint defaultObj("", 0, 0);
double val1, val2;
val1 = passedObj.calculateDistance(defaultObj);
val2 = calculateDistance(defaultObj);
if (val1 > val2)
{
return (b = 1);
}
else
{
return (b = 0);
}

}
the line in bold throws an error and the function calculateDistance works just fine. However when i replace that line with this:

ClassName copyPassedObj = passedObj;
val1 = copyPassedObj.calculateDistance(defaultObj);

it works fine again. I really dont understand the reason behind this.
Could someone please explain?
It is probably that the function calculateDistance has not indicated to the compiler that it is safe to execute on constant objects. For example:
1
2
3
4
5
6
7
8
9
class MyClass
{
    int x;
public:
    int GetTheValueOfX()
    {
        return x;
    }
};
The function getTheValueOfX does not actually change anything in the class, but the compiler doesn't know this. You have to tell it explicitly:
1
2
3
4
5
6
7
8
9
class MyClass
{
    int x;
public:
    int GetTheValueOfX() const
    {
        return x;
    }
};
Now the compiler knows that this function is OK to be called for constant objects and i will not give you any error when you do so.


The reason it works when you copy it is because the copy is not constant but the copy constructor can accept a constant object to copy from.
Last edited on
Thank you! It works now.
Topic archived. No new replies allowed.