Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's with pointers in C++?

Tags:

c++

pointers

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!

like image 822
mikhailcazi Avatar asked Dec 16 '22 03:12

mikhailcazi


2 Answers

That book is wrong because it should be:

ABC *q;
q = &obj;
q->getdata();

Or using a int pointer:

ABC *q;
int *qq;
qq = &obj.data;
q = &obj;
q->getdata();
like image 54
Daniele Vrut Avatar answered Dec 24 '22 11:12

Daniele Vrut


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();.

like image 37
Spook Avatar answered Dec 24 '22 11:12

Spook