Click to See Complete Forum and Search --> : C++ class pointer confusion


nanode
03-21-2001, 02:08 PM
I'm a lazy Java coder and I'm stuck with a likely simple problem.

I have 2 functions:

Function A creates an instance of a Collection class and passes a ref. of that Collection to Function B.

Function B needs to add elements to said Collection, but my compiler isn't allowing that, since I only have a pointer to the Collection.


void functionA() {
Collection c;
functionB(&c);
}

void functionB(Collection * cref) {
cref.add(xxx);
}



Am I doing this completely wrong?

7
03-21-2001, 02:46 PM
Hi
Im very new, someone will probably correct me tho. Should that be,

(*cref).add(xxx); ? to dereference the pointer?

or
cref->add(xxx); ?

kmj
03-21-2001, 03:27 PM
7 is right; either one of those will work.

OR

you may want to consider having a reference to the object as the argument, instead of a pointer.



void functionB(Collection &cref) {
cref.add(xxx);
}


edit: oh yeah; if you do it this way, you don't need to pass the address of the arguement to the function, just the function, so the whole thing would be:



void functionA() {
Collection foo;
functionB(foo);
}

void functionB(Collection &cref) {
cref.add(xxx);
}


[ 21 March 2001: Message edited by: kmj ]

nanode
03-21-2001, 03:30 PM
kmj:

I figured it was best to do as you suggested. <plug>That's how java does it...</plug>

Thanks for the replies.

kmj
03-21-2001, 03:31 PM
;) I like java; don't have the opportunity to play with it enough, though.