Jonathan Layduhur
Jonathan Layduhur

Reputation: 93

C++ : pointer on member function


namespace Borg
{
 class BorgQueen
 {
 public:
   BorgQueen();
   bool move(Borg::Ship *ship, Destination dest) {return ship->move(dest);}
   void fire(Borg::Ship *ship, Federation::Starfleet::Ship *target) {ship->fire(target);}
   void destroy(Borg::Ship *ship, Federation::Ship *target) {ship->fire(target);}
 
   void (Borg::BorgQueen::*firePtr)(Borg::Ship *ship, Federation::Starfleet::Ship *target) = &Borg::BorgQueen::fire;
   void (Borg::BorgQueen::*destroyPtr)(Borg::Ship *ship, Federation::Ship *target) = &Borg::BorgQueen::destroy;
   bool (Borg::BorgQueen::*movePtr)(Borg::Ship *ship, Destination dest) = &Borg::BorgQueen::move;
 };
};

I need to have a pointers on mebers of my class : movePtr -> move(); This is what I have mannage to comme whit but i access it (the pointer); how can i call it from the ptr ?

int main()
{
   Borg::BorgQueen Q();
   [...]
   // this does work 
   Q.movePtr(...);
   Q.*movePtr(...);
   *(Q.movePtr)(...)


}

Upvotes: 0

Views: 59

Answers (1)

molbdnilo
molbdnilo

Reputation: 66371

The right-hand side of .* is not resolved in the context of the left-hand side, but in the current scope.

Like this:

int main()
{
    bool (Borg::BorgQueen::*go)(Borg::Ship *ship, Destination dest) = &Borg::BorgQueen::move;
    Borg::BorgQueen queen;
    //...
    (queen.*go)(something something...);
}

Q is your object, the name of its member is Q.movePtr, the "dereference pointer-to-member" operator is .*, so you need

(Q.*Q.movePtr)(...);

Pointers-to-members seem very neat until you notice that they easily make your code completely unreadable.

Upvotes: 1

Related Questions