Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with pointers and vectors 1

Status
Not open for further replies.

fugigoose

Programmer
Jun 20, 2001
241
0
0
US
Hokay. So I have a vector of pointer to my class. We'll call it myClass. So the code is

vector <myClass> collection;
collection.push_back(new myClass);

So all that seems to work fine. Now, I need to set up some of the class instances properties. This is where i run into trouble:

collection[0].someProperty = 432;

This doesn't work, it say 'item to the left of ".someProperty" must have a struct/type/union bla bla bal"

I'm not sure if this is caused my lack of knowledge about vectors or pointers. Can you work with a pointer to class instance the same way you would an actual instance? I need a dynamic array of class instances, but I also need to be able to customize each one. Thank you.
 
In:

Code:
vector <myClass> collection;
collection.push_back(new myClass);

collection contains myClass objects, but you try to put a myClass* into there.

You probably want collection to be of type vector<myClass*>.

(I think you might have that part right in your code and just made a typo, since you said "vector of pointer to my class").


Now, assuming you have a vector<myClass*>, you would access the members of each element (a myClass*) by using the -> operator.

So...

Code:
collection[0]->someProperty = 432;

or, having the exact same meaning:

Code:
(*(collection[0])).someProperty = 432;
 
So...

> Can you work with a pointer to class instance the same way you would an actual instance?

No. You have to dereference a pointer before being able to treat it like it's the thing it's pointing to. That's what happens in the last piece of code I put.

The second to the last, using the -> operator, does the exact same thing, but is neater and more direct. The -> operator acts like a combination of a dereference (*) and a member selection (.).
 
>I need a dynamic array of class instances

Perhaps consider skipping the new.

ie
Code:
vector <myClass> collection;
myClass m;
collection.push_back(m);

You then dont have to worry about deleting etc. On the other hand, its a bad thing to do if you want to store derived classes in the same array (in that case pointers should be used).

/Per
[sub]
&quot;It was a work of art, flawless, sublime. A triumph equaled only by its monumental failure.&quot;[/sub]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top