0

I am working on some source codes grabbed from Internet and find a confused sentence.

map<int, Element* (*) (int, Domain*) > elemList

My question is for the value part of elemList. Is is a pointer ? Or constructor function? Or some else ?

Best regards

wenlu Yang
  • 21
  • 1
  • It's a function pointer. Look where the map is used. – Retired Ninja Jan 30 '21 at 05:27
  • If we follow [the clockwise/spiral rule](http://c-faq.com/decl/spiral.anderson.html) then `Element* (*) (int, Domain*)` is a pointer to a function (taking one `int` and one `Domain*` argument) that returns a pointer to `Element`. [Decent books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) should have mentioned function pointers. – Some programmer dude Jan 30 '21 at 05:30
  • @RetiredNinja I would like to express my thanks for your attention and your answer. – wenlu Yang Jan 30 '21 at 13:00
  • @Someprogrammerdude: Thanks for your nice and detailed explanation. – wenlu Yang Jan 30 '21 at 13:00

1 Answers1

1

Element* (*) (int, Domain*) is for function pointers. These are of two types.

  • Raw function pointers (which is something like this: void (*foo)(int x, int y);).
  • Member function pointers (which looks something like this: void (Object::*foo)(int x, int y);).

In a raw function pointer, its made of 3 parts. Lets use the above example,

  1. Return type (which is void).
  2. Function name/ pointer name (which is foo).
  3. Function parameters (which is (int x, int y)).

In a member function pointer, its made of 4 parts.

  1. Return type (which is void).
  2. Which class/ struct holds the function (which is Object).
  3. Function name/ pointer name (which is foo).
  4. Function parameters (which is (int x, int y)).

Calling a raw function pointer is as easy as this,

void Func(int x, int y) { ... }

void (*foo)(int x, int y) = Foo;    // Assigning the function pointer.
foo();    // Calling the pointer.

Calling a member function pointer is slightly different. For this you need a valid instance of the object.

class Object {
public:
    void Func(int x, int y) { ... }
};


void (Object::*foo)(int x, int y) = &Object::Func;    // Assigning the function pointer. Notice the '&' operator here.

Object object;
(object.*foo)();    // Calling the function pointer.

So what map<int, Element* (*) (int, Domain*) > elemList does is, it stores a map of raw function pointers which is mapped to an integer.

Additional: In order to assign a function to a function pointer, these things should match,

  • The return type.
  • Parameters of the function.
  • The object which holds the function (this is only for member functions).
D-RAJ
  • 3,263
  • 2
  • 6
  • 24