Ian
Ian

Reputation: 169

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.

Upvotes: 3

Views: 348

Answers (1)

James McNellis
James McNellis

Reputation: 355337

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

(point->*getCoordinate)(); 

Upvotes: 6

Related Questions