• Advertisement
Sign in to follow this  

(cpp) how to return a pointer to a vector array and access it?

This topic is 4202 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi I've got my World class returning a pointer to a vector array of the Smoke class:
class Smoke {
public:
	D3DXVECTOR3 position;
};

class World {
private:
	vector<Smoke> smokes;
public:
vector<Smoke>* getSmokes() {
	return &smokes;
}

And I when trying to access the get function, I get an error eg: D3DXVECTOR3 p = world->getSmokes()[0].position; returns the error:
Quote:
error C2039: 'position' : is not a member of 'std::vector<_Ty>' with [ _Ty=Smoke ]
I don't see whats wrong here, and are there any alternate ways of returning the array that you would recommend?

Share this post


Link to post
Share on other sites
Advertisement
I would recommend return a reference instead of a pointer. However, if you want to use a pointer you need to dereference the pointer before indexing it. i.e.: (*(world->getSmokes()))[0].position;

Share this post


Link to post
Share on other sites
I believe the compiler is acting as though you're trying to access an array of vectors. It's like this:

vector<something> *vectors;
vectors[0] <- the first pointer, not the first element

Deferencing the return would probably fix the problem.

(*(getSmokes()))[0].position;

although that looks really ugly. Why not return a reference?

Edit: Beaten :(

Share this post


Link to post
Share on other sites
I agree with SiCrane. Change your code to -
vector<Smoke>& getSmokes() {
return smokes; // without & operator
}

And you should get the behavior you want.

Share this post


Link to post
Share on other sites
Of course, providing access to internal variables is frequently a sign of a borked design.

Why is World providing access to the vector, rather than providing functions to manipulate the Smoke for client code?

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement