0

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)(...)


}
  • Possible duplicate? https://stackoverflow.com/questions/14814158/ – Drew Dormann Jan 13 '21 at 16:01
  • I don't understand the question. "_how can i call it from the ptr_" and then you say "_this does work_". You seem to have figured out that you need a `BorgQueen` instance. So, what's the question really? Perhaps you should just store a pointer to the `BorgQueen` instance instead and call its move function directly? – Ted Lyngmo Jan 13 '21 at 16:03
  • 1
    Seems like a reimplementation of what `virtual` already does. Unless this is academic, consider using a polymorphic class instead. – François Andrieux Jan 13 '21 at 16:08

1 Answers1

1

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.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82