Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 238
mike Avatar asked Nov 23 '25 08:11

mike


2 Answers

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.

like image 195
jrok Avatar answered Nov 26 '25 00:11

jrok


Declare num_points as const, too:

int num_points() const
{
    return _points.size();
}
like image 24
Kerrek SB Avatar answered Nov 26 '25 01:11

Kerrek SB