avd avd -4 years ago 185
C++ Question

C++ const qualifier

I have a Point2D class as follows:

class Point2D{
int x;
int y;
Point2D(int inX, int inY){
x = inX;
y = inY;

int getX(){return x;};
int getY(){return y;};

Now I have defined a class

class Line {
Point2D p1,p2;
LineVector(const Point2D &p1,const Point2D &p2):p1(p1),p2(p2) {
int x1,y1,x2,y2;

Now the compiler gives the error in the last line( where
etc are called):

error: passing
const Point2D
argument of
int Point2D::getX()
discards qualifiers

If I remove the
keyword at both places, then it compiles successfully.

What is the error? Is it because
etc are defined inline? Is there any way to rectify this retaining them inline?

Answer Source

You have not declared getX() and getY() methods as const. In C++, you can only call const methods from a const object. So your function signature should be int getX() const{..}. By defining them as the const method you are telling the compiler that you are not going to modify any member variable inside this method. Since your object is a const object, it is not supposed to be modified hence you can call only call const methods on it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download