Pointer of objects

I know that pointer means a variable that's store the address of the pointed object. (Tell me if anything wrong, and help me to figure it out please.)Here's the thing that I don't understand.

Suppose we using int*
1
2
3
  int *a;
  *a = 2;
  std::cout << *a;

In this case, the output would be
 
 2 

And *a means the value of the address in which a is pointing to.

And the problems comes.
1
2
3
4
5
6
7
8
9
10
class abc
{
public:
  void sth(){std::cout << 2};
};
int main()
{
  abc* aclass;
  aclass->sth();
}

In this example, why we need to use aclass->sth(); to access the class member function, but cannot be *aclass->sth();?
Hi Jacfger

well your explanation is correct but example is not.

imagine you have a box called box a, in that box you can only put an address. So what you do in your code is i am creating a box a, then I am trying to put a value in that box. So obviously that is not going to fit.
what you could do is this:

1
2
3
int value_stored_in_box = 2; // this is normal integer
int* a = value_stored_in_box ; // this is creating pointer, initializing it with address to  value_stored_in_box


remember there are at least 2 values connected to normal variable
1. Its address in memory
2. value it stores

with pointers there are 3 "values" connected/associated
1. address where pointer is pointing.
2. value of the address where pointer is pointing
3. pointer its own address


hope this helps :)
Last edited on
You could write this:
 
    aclass->sth();

or this:
 
    (*aclass).sth();

They both do the same thing, the first version is often more convenient.

see tutorial
http://www.cplusplus.com/doc/tutorial/structures/

Last edited on
@xxvms
I see your post was well-intentioned, I also noticed the problems in the OP. However your example contains an error:
Original example:
1
2
int value_stored_in_box = 2; // this is normal integer
int* a = value_stored_in_box ; // this is creating pointer, attempting to assign an integer  


The second line should be:
 
int* a = &value_stored_in_box ; // initialize pointer with address of value_stored_in_box 


Notice the & operator, which gets the address of the variable.
Last edited on
Chervil

Yes you are of course right! I missed &

Shame on me! 😄

My tutor would be crossed with my clumsiness.
Topic archived. No new replies allowed.