mike
mike

Reputation: 1322

Use of const pointer to class in function

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!

Upvotes: 2

Views: 4445

Answers (2)

jrok
jrok

Reputation: 55425

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.

Upvotes: 10

Kerrek SB
Kerrek SB

Reputation: 477640

Declare num_points as const, too:

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

Upvotes: 6

Related Questions