-1
class Person;
class Command {
 private:
    Person * object;
    //what is this? - a functor?...
    void (Person::*method)();
 public:
    Command(Person *a, void(Person::*m() = 0): object(a),method(m) {}
    void execute() { (object->*method(); }
 };

// defining class Person here
class Person {
 private:
    string name;
    Command cmd;
 public:
    Person(string a, Command c): name(a),cmd(c) {}
    void talk();
    void listen();
};

I was wondering what line 6 here means? Is that a way of defining a function or a functor? Also where does this type of function def appear and tends to be used? I found this example Under "Design Patterns" within Object Oriented Programming - this approach type is called Behavioural Command Pattern.

coder3101
  • 3,920
  • 3
  • 24
  • 28
user15736
  • 13
  • 4

2 Answers2

1

This is a pointer to Person class member taking no parameters and returning void. Such initialization allows class Command referring to custom methods of class Person. Imagine class Person to be defined like this:

class Person
{
public:
    void f1() { std::cout << "Call f1\n"; }
    void f2() { std::cout << "Call f2\n"; }
};

Then we can create Command objects in this way:

Person p;
Command c1(&p, &Person::f1);
Command c2(&p, &Person::f2);

Executing these commands calls corresponding methods of given person:

c1.execute(); // prints "Call f1"
c2.execute(); // prints "Call f2"
Valery Kopylov
  • 383
  • 1
  • 7
-1

This code line void (Person::*method)(); is a function pointer. void means that the function that is pointed won't return any data. (Person::*method)() is the definition of the pointer, the pointer will point to a void function.

In this page you can see how the syntax is:

Function Pointer Syntax

The syntax for declaring a function pointer might seem messy at first, but in most cases it's really quite straight-forward once you understand what's going on. Let's look at a simple example:

void (*foo)(int);

In this example, foo is a pointer to a function taking one argument, an integer, and that returns void. It's as if you're declaring a function called "*foo", which takes an int and returns void; now, if *foo is a function, then foo must be a pointer to a function. (Similarly, a declaration like int *x can be read as *x is an int, so x must be a pointer to an int.)

The key to writing the declaration for a function pointer is that you're just writing out the declaration of a function but with (*func_name) where you'd normally just put func_name.

CryogenicNeo
  • 937
  • 12
  • 25