What's with pointers in C++?
c++, pointers
Solution
ABC * q
This instruction creates to pointer to fragment of memory, where resides instance of class ABC. For example:
q = new ABC();
This instantiates ABC and stores address of that instance in q variable.
ABC abc;
q = &abc;
This instantiates ABC automatically (that means, compiler takes care of allocation and deallocation of that instance) and stores address to that class in q.
Also, `->` is not pointer to member function operator. This is only shorter way of writing something else:
a -> b
equals
(*a).b
If you know, that `a` points to a class instance (or struct instance, what in C++ is more less the same) and you want to access a member (field or method) of that instance, you can quickly write `a->b = 5;` or `a->DoSth();` instead of `(*a).b = 5;` or `(*a).DoSth();`.
Problem
I'm having some trouble understanding the use of pointers in this program: ``` #include<iostream.h> class ABC { public: int data; void getdata() { cout<<"Enter data: "; cin>>data; cout<<"The number entered is: "<<data; } }; void main() { ABC obj; int *p; obj.data = 4; p = &obj.data; cout<<*p; ABC *q; q = &obj.data; q->getdata(); } ``` I get everything until the following step : `ABC *q;` What does that do? My book says it's a class-type pointer (it's very vague with pathetic grammar). But what does that mean? A pointer pointing to the address of the class ABC? If it is, then the next step confuses me. `q = &obj.data;` So we're pointing this pointer to the location of data, which is a variable. How does that `ABC *q;` fit in, then? And the last step. What does `q->getdata();` do? My book says it's a 'pointer to member function operator', but gives no explanation. Glad to recieve any help!