-   Programming (
-   -   arrays of pointers to class objects (

tdurden 11-18-2002 03:02 PM

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
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?

tdurden 11-18-2002 03:04 PM

P.S I just started using linux, and my computer is running redhat 8.0 I think, whatever the latest version is.

llama_meme 11-18-2002 05:08 PM

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.


tdurden 11-18-2002 10:27 PM

Yes that works for integers, but it's not the same for class objects. Try it if you don't believe me.

llama_meme 11-20-2002 07:47 AM

Well I've tried it, and it works for me on gcc 2.95.4. This program works as expected:


#include <cstdio>
using namespace std;

class Foo
        int bar;
                bar = 5;

int main(int argc, char **argv)
        Foo *foos = new Foo[5];

        printf("%i\n", foos[2].bar);

        return 0;

Btw, the [] operator DOES dereference the pointer - someArray[x] is just shorthand for:

/* 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...


bgraur 12-16-2002 11:47 AM


Obj *pntr = new Obj[5];
According to this declaration pntr is a pointer to an array of five Obj objects, not an array of pointers to Obj objects how you wanted.
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 04:12 AM.