pointers and objects, another question.

Hi,

I am confused with pointers to objects. Suppose I have a class by name "be_int".
Now, when I create a pointer to the object and allocate memory this way,
1
2
be_int* ix;
ix = new be_int [10];

Then, I am able to access the member functions only using the . operator and not the -> operator (I expected that I could access using the -> operator). For example,

1
2
3
4
5
for (int i=0; i<10; i++ ) {
ix[i].getData();
}
// free
delete[] ix;


Now, if I create it as an array of pointers
1
2
3
4
5
6
7
8
9
be_int *ix[10];
for (int i=0; i<10; i++) {
ix[i] = new be_int;
ix[i]->getData(); // using -> alone works here.
}

...
...
// run a for-loop again and remove all allocated pointers to ix. 


What's the difference here? I have coded it so many times before but this is one of those times where I just couldn't remind myself of the difference!!!

thank you!
-> takes a pointer on the left side
. takes an object on the left side
[] dereferences a pointer (ie: turns a pointer into an object)
[] also indexes an array (ie: turns an array of objects into a single object)

SO

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
be_int* ix;  // ix is a pointer, therefore

ix;  // a pointer
ix[0];  // the [0] dereferences the pointer, therefore this is an object
*ix;  // this is the same as ix[0].  This is an object

ix->GetData();  // since 'ix' is a pointer, use ->
ix[0].GetData();  // since 'ix[0]' is an object, use .
(*ix).GetData();  // since '*ix' is an object, use .

//==========
be_int *ix[10];  // ix is an array of pointers

ix;  // an array of pointers
ix[0];  // one of the pointers in the array
*ix[0];  // an object

// so....
ix[0]->GetData();  // because ix[0] is a pointer, use ->
(*ix[0]).GetData();  // because *ix[0] is an object, use . 
Topic archived. No new replies allowed.