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

Started by
3 comments, last by JasonBlochowiak 17 years, 8 months ago
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?
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;
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 :(
I agree with SiCrane. Change your code to -
vector<Smoke>& getSmokes() {	return smokes; // without & operator}

And you should get the behavior you want.
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?

This topic is closed to new replies.

Advertisement