This is a two-part question.
1. I'm trying to understand how to use the pointer-to-member access operator but I don't understand the example code provided by [1].
Specifically, I don't understand what's being declared on line 17 and 18:
17 18
|
int S::* pmi = &S::mi;
int (S::* pf)(int) = &S::f;
|
Line 17 looks like the initialization of a pointer
pmi
but what the heck is
int S::
part of the type? Does it mean "an int, but not just any int; an int that must be inside the class S"? I guess it could also be a "scoped pointer", as in, "an S-class member pointer that is an int". -\_( o.O)_/-
Line 18 looks like a function pointer initialization (
pf
is a pointer to a function that takes int and returns an int). But, again, what the heck is up with
S::
?
2. Does
lhr->*rhs
mean
*(*(lhs).rhs)
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include <iostream>
struct S
{
S(int n): mi(n) {}
mutable int mi;
int f(int n) { return mi + n; }
};
struct D: public S
{
D(int n): S(n) {}
};
int main()
{
int S::* pmi = &S::mi;
int (S::* pf)(int) = &S::f;
const S s(7);
//s.*pmi = 10; // error: cannot modify through mutable
std::cout << s.*pmi << '\n';
D d(7); // base pointers work with derived object
D* pd = &d;
std::cout << (d.*pf)(7) << ' '
<< (pd->*pf)(8) << '\n';
}
|
So
(pd->*pf)(8)
is a function invocation and my hypothesis is that it is equivalent to
*(*(pd).pf)(8)
[1] cppref: C++ Operator Precedence
https://en.cppreference.com/w/cpp/language/operator_member_access#Built-in_pointer-to-member_access_operators