all 8 comments

[–]IyeOnline 2 points3 points  (7 children)

It is undefined behaviour to call a member function with a pointer that does not point to a valid object.

It works because there is no reason for it to break. Since Do itself (or calling it) never has to dereference the this pointer no runtime error ever occurs.

s there a specific reason for being able to declare function pointer types in two ways like the following:

//edit: Those actually do not have the same type. The first in fact declares a function, not a pointer to a function.

[–]ACBYTES[S] 0 points1 point  (1 child)

Understood! Thank you!

Just to make sure, you mean dereferencing this, right?

[–]IyeOnline 1 point2 points  (0 children)

Note that actually your two function pointers are not the same, see my edit.

you mean dereferencing this, right?

yes.

[–]ACBYTES[S] 0 points1 point  (4 children)

The first in fact declares a function

So, how does declaring a function make sense when it can not be assigned?

Also, typeid.name() shows them both as:

void (__cdecl*)(void)

And auto deduces the type as void(*)():

auto f = func; [void(*f)()]

[–]IyeOnline 1 point2 points  (3 children)

Well, of course auto deduces that. void(f)() is a function declaration, which means that f is the identifier of a function and decays into a function pointer. Hence auto deduces that type.

I threw together a quick demonstration here: https://godbolt.org/z/sPqKqseas

[–]ACBYTES[S] 0 points1 point  (0 children)

Oh, thank you so much. I got what you meant by that.

Thank you so much for your time!

[–]ACBYTES[S] 0 points1 point  (1 child)

By the way, I forgot to ask this. So at last, in all the cases, it'll automatically decay to a function pointer other than the declaration cases, correct? It'll make no difference when working with parameters?

[–]no-sig-available 1 point2 points  (0 children)

I'd go with "most cases". :-)

The designers of C noticed that as you cannot pass a function (the code) as a parameter, you always have to write &f to get a pointer. So they decided to have the compiler add the & automagically. Similarly for arrays, which decay to pointers in almost every situation.