Yes, I've seen this question and this FAQ, but I still don't understand what ->*
and .*
mean in C++.
Those pages provide information about the operators (such as overloading), but don't seem to explain well what they are.
What are ->*
and .*
in C++, and when do you need to use them as compared to ->
and .
?
Correct Option: D. The pointer to member operators . * and ->* are used to bind a pointer to a member of a specific class object.
2) Pointer to member declarator: the declaration S C::* D; declares D as a pointer to non-static member of C of type determined by decl-specifier-seq S . There are no pointers to references and there are no pointers to bit fields.
Pointers to members allow you to refer to nonstatic members of class objects. You cannot use a pointer to member to point to a static class member because the address of a static member is not associated with any particular object. To point to a static class member, you must use a normal pointer.
C++ provides two pointer operators, which are Address of Operator (&) and Indirection Operator (*). A pointer is a variable that contains the address of another variable or you can say that a variable that contains the address of another variable is said to "point to" the other variable.
I hope this example will clear things for you
//we have a class struct X { void f() {} void g() {} }; typedef void (X::*pointer)(); //ok, let's take a pointer and assign f to it. pointer somePointer = &X::f; //now I want to call somePointer. But for that, I need an object X x; //now I call the member function on x like this (x.*somePointer)(); //will call x.f() //now, suppose x is not an object but a pointer to object X* px = new X; //I want to call the memfun pointer on px. I use ->* (px ->* somePointer)(); //will call px->f();
Now, you can't use x.somePointer()
, or px->somePointer()
because there is no such member in class X. For that the special member function pointer call syntax is used... just try a few examples yourself ,you'll get used to it
EDIT: By the way, it gets weird for virtual member functions pointers.
For member variables:
struct Foo { int a; int b; }; int main () { Foo foo; int (Foo :: * ptr); ptr = & Foo :: a; foo .*ptr = 123; // foo.a = 123; ptr = & Foo :: b; foo .*ptr = 234; // foo.b = 234; }
Member functions are almost the same.
struct Foo { int a (); int b (); }; int main () { Foo foo; int (Foo :: * ptr) (); ptr = & Foo :: a; (foo .*ptr) (); // foo.a (); ptr = & Foo :: b; (foo .*ptr) (); // foo.b (); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With