Battleroid
Battleroid

Reputation: 881

Constant functions can't be used on constant referenced object?

I'm not entirely sure how to describe my issue at all.

Basically I have a function that checks to see if my rectangle contains a different rectangle, however, when I attempt to use my functions such as getX and getY I am met with: Error: the object has type qualifiers that are not compatible with the member function object type is: const Rectangle2D.

My function is below.

const bool Rectangle2D::contains(const Rectangle2D &r) {
    const double x = r.getX();
    const double y = r.getY();
    const double width = r.getWidth();
    const double height = r.getHeight();
}

All of my get functions are constant, example:

const double Rectangle2D::getX() {
    return x;
}

And in my class it the function is defined as const bool contains(const Rectangle2D &r).

If more information is needed let me know. I would appreciate it if someone could help me out or point me in the right direction.

Upvotes: 0

Views: 205

Answers (2)

Dave Johnson
Dave Johnson

Reputation: 411

You need to put const after the function name and parameter list, before the curly brace or semicolon. So in your class you should have

double getX() const;

And then when you implement it, you should have

double Rectangle2D::getX() const {
    return x;
}

You'll need to do the same with the contains function and any other functions you want to be able to use on a const Rectangle2D.

Upvotes: 4

Beta
Beta

Reputation: 99094

Done this way:

const double Rectangle2D::getX() {
    return x;
}

this is a non-const function that returns a constant double.

To make it a const function, do it like this:

double Rectangle2D::getX() const {
  return x;
}

Upvotes: 2

Related Questions