Not Sure how to fix error message

SO, the short of the program is to create a Point class with set/get and distanceTo functions. Then create a lineSegment class that will create Point objects and then use the distanceTo function to determine the length of the line between point and use a slope function to determine slope. llineSegemnt has a main() to input the coordinates for the points and call the functions for slope and length.
Anyway I think I have it all set but I get this error when I try to compile either .cpp, line 46/47 error: passing 'const Point' as 'this' argument of double 'Point::getXCoord()' discards qualifiers.

I gather there is an issue with use a double function in a function that uses a const ref parameter may be the issue, but Im not sure how to fix it.

Here is the header:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  
#ifndef POINT_H
#define POINT_H


class Point
{
    private:
        int x_Coord;
        int y_Coord;

    public:
        void setXCoord(double);
        double getXCoord();
        void setYCoord(double);
        double getYCoord();
        double distanceTo(const Point&);
        Point(double, double);
        Point();

};

#endif // POINT_H 

and here is the .cpp:
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
42
43
44
45
46
47
48
49
50
51
#include "Point.hpp"
#include "lineSegment.hpp"
#include <iostream>
#include <cmath>

using namespace std;



Point::Point(double x, double y)
    {
        x_Coord = x;
        y_Coord = y;
    }

Point::Point()
    {
        x_Coord = 0;
        y_Coord = 0;
    }

 void Point::setXCoord(double x)
 {
     x_Coord = x;
 }

 double Point::getXCoord()
 {
     return x_Coord;
 }

 void Point::setYCoord(double y)
 {
     y_Coord = y;
 }

 double Point::getYCoord()
 {
     return y_Coord;
 }

 double Point::distanceTo(const Point &p2)
 {
      double deltaX, deltaY;

      deltaX = x_Coord - p2.getXCoord();
      deltaY = y_Coord - p2.getYCoord();

     return sqrt((deltaX * deltaX) + (deltaY * deltaY));
 }

I apologize for the formatting my code is a little raw.
Line 42: You've declared the argument as const Point & p2. You're making a promise to the compiler that you're not going to modify p2.

Line 46: You're calling p2.getXCoord() which is not declared as a const function. Therefore the compiler assumes that getXCoord() can modify p2, which violates the constness of p2 which you declared at line 42. This is what the error message is trying to tell you.

getXCoord() and getYCoord() should be const functions for two reasons: 1) because they don't modify the Point instance and 2) so they can be called from a const function such as distanceTo().
Last edited on
Thank you, that did it. I had to add 'const' after the function to make it a constant function.
Topic archived. No new replies allowed.