Sign in to follow this  
johnnyBravo

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

Recommended Posts

johnnyBravo    100
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
SiCrane    11839
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
Scet    960
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
Mushu    1396
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this