Asking about typedef

Hello

I would like to know what is the meaning of the following expression :

typedef bool (*compareShapes)(const Shape* s1, const Shape* s2);

Shape is the name of a class
Thanks
A general rule of thumb I find useful is to read C++ declarations like Arabic i.e from right to left to figure out what what they mean:
http://www.cplusplus.com/forum/beginner/202293/

So let's begin with this one:

typedef bool (*compareShapes)(const Shape* s1, const Shape* s2);
First, let's consider any one of the function parameters, say s1:

s1 is a variable
s1 is a pointer variable
s1 is a pointer variable to type Shape
s1 is a pointer variable to type const Shape ...
similarly for s2

Now for the typedef bit - here we are defining a type where the type is not a variable or class or struct but a function pointer and the weird thing about function pointer typedefs is that the type definitions name is not the declaration's last element but smack bang in the middle, here it's compareShapes
So now that we have a type we can write
1
2
3
4
5
6
7
8
compareShapes cS = &foo;//similar fashion to C-style arrays, name of the function returns the function's address; 
where foo is some function of the form:

bool foo (const Shape* s1, const Shape* s2);

and then we can call the function through the pointer in the following manner:

bool foo_ptr = compareShapes(s1, s2) where s1 and s2 are both const Shape*



Last edited on
Topic archived. No new replies allowed.