Split
Split

Reputation: 299

No suitable conversion function from std::vector<Object *, std::allocator<Object *>>" to "Object *" exists

Not sure where I'm going wrong.. I have two classes like so:

class One
{
    public:
    vector<Object*> myObjects;
};

class Two
{
    public:
    vector<Object*> * pointertoObjects;
};

I then want to create a pointer from pointertoObjects to myObjects and am doing so like this:

pointertoObjects = &myObjects;

But when I try to access to pass through an element:

void doFunction(Object * object);
doFunction(pointertoObjects[i])

it gives me an error:

Error: no suitable conversion function from std::vector<Object *, std::allocator<Object *>>" to "Object *" exists

Where have I gone wrong?

Upvotes: 1

Views: 11945

Answers (4)

wachme
wachme

Reputation: 2337

vector<Object*> pointedObjects = *pointertoObjects;
Object* obj = pointedObjects[i]
doFunction(obj);

Upvotes: 0

syam
syam

Reputation: 15089

When you write pointertoObjects[i], you are dereferencing pointertoObjects and C++ behaves like it was an array of vector<Object*>, so pointertoObjects[i] yields a (reference to) vector<Object*>.

To fix that:

(*pointertoObjects)[i]

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254631

pointertoObjects[i]

This treats the pointer as the address of the start of an array of vector objects, and gives you element i of that array. (Since there isn't an array, just a single vector, you'll get undefined behaviour if i is non-zero).

If you want element i of the vector that the pointer points to, then that's:

(*pointertoObjects)[i]

or with range-checking and less scope for accidental type errors:

pointertoObjects->at(i)

You should ask yourself whether you really need so many pointers; they can get quite confusing.

Upvotes: 6

Scott Jones
Scott Jones

Reputation: 2906

You have a simple type mismatch. When you use array indexing on pointertoObjects, you get a reference to a vector<Object*>, not the Object * required by doFunction.

You probably want something like this: doFunction((*pointertoObjects)[i]);

Upvotes: 0

Related Questions