arrays of pointers to class objects
I 've been searching for an answer to this like a madman and found nothing, so please help. If I have an array of pointers to class objects, I can only access member functions using the dot operator as opposed to the arrow operator. i.e
Obj *pntr = new Obj[5]; obj[0].func(); //I have to use this syntax as opposed to obj[0]->func(); Is my compiler on crack? when I use the g++ compilers at my school, they tell me to change my major if I use the dot operator like this. But the compiler at home chokes on the arrow operator and says:"base is of non Obj pointer type" as if the '[]' operator is dereferencing the pointer. The weird thing is that if I have just a single pointer to a class object, I have to use the arrow operator to access member functions. Has there been some change in C++ pointer syntax that I'm unaware of? |
P.S I just started using linux, and my computer is running redhat 8.0 I think, whatever the latest version is.
|
obj[x] gives you an object, not a pointer to an object, so you have to use a dot.
if you had: int *foo = new int[7] then foo[2] would be an int, not a pointer to an int. Alex |
Yes that works for integers, but it's not the same for class objects. Try it if you don't believe me.
|
Well I've tried it, and it works for me on gcc 2.95.4. This program works as expected:
Code:
#include <cstdio> /* Nasty pointer arithmetic */ *(someArray + x) Therefore [] will always give you a value one level of reference lower than the value it was applied to; i.e. a pointer a goes to a value, a pointer to a pointer goes to a pointer, etc... Alex |
Quote:
If you wanted an array of pointers to Obj objects you must declare pntr like this : Obj **pntr = new *Obj[5]; Now pntr points to an array of five pointers to Obj objects. You must allocate each pointer in the array to point to a valid memory space: pntr[i] = new Obj(); for each i in [0,4]; |
All times are GMT -5. The time now is 11:09 AM. |