2

I am using std::shared_ptr liberally in my code. I have a few functions that I want to call from MyClass using "this" so have declared these functions as (for example)

int AnotherClass::foo(const MyClass *obj)
{
} 

I want the const to make it clear obj is not going to get changed since I am passing a raw pointer. However inside foo I have

int AnotherClass::foo(const MyClass *obj)
{
    int number = obj->num_points()-1;
}

and my compiler is complaining that "the object has type qualifiers that are not compatible with the member function". num_points is a simple get function declared and defined in the header:

class MyClass {
public:
  ...
  int num_points(){return _points.size();}
  ...
private:
  std::vector<MyPoint> _points;
};

What's the best way around this? Obviously I can get rid of the const requirement in foo but I like the rigidity it imposes. Many thanks in advance!

mike
  • 1,192
  • 9
  • 32

2 Answers2

10

Make that member function const:

int num_points() const // <---
{
    return _points.size();
}

This way you can call it on const objects. Get in the habbit to qualify like this every function that doesn't alter the object's state.

jrok
  • 54,456
  • 9
  • 109
  • 141
6

Declare num_points as const, too:

int num_points() const
{
    return _points.size();
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084