Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to member function

I have the following class:

class Point2D
{
    protected:

            double x;
            double y;
    public:
            double getX() const {return this->x;}
            double getY() const {return this->y;}
   ...

};

Sometimes I need to return x coordinate, sometimes y coordinate, so I am using pointer to the member function getX(), getY(). But I am not able tu return coordinate, see below, please.

double ( Point2D :: *getCoord) () const;

class Process
{
   ......
   public processPoint(const Point2D *point)
   {

      //Initialize pointer
      if (condition)
      {
         getCoord = &Point2D::getX;
      }
      else
      {
         getCoord = &Point2D::getY;
      }

      //Get coordinate
      double coord = point->( *getCoordinate ) (); //Compiler error

   }

}

Thanks for your help.

like image 764
Ian Avatar asked Jun 03 '26 20:06

Ian


1 Answers

You need to use the ->* operator to call a member function via a pointer:

(point->*getCoordinate)(); 
like image 163
James McNellis Avatar answered Jun 06 '26 09:06

James McNellis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!