Blender
Blender

Reputation: 298532

invalid initialization of non-const reference of type ‘std::vector<Object*>&’

I've just started out with C++ because I want to translate my raytracer from Python into C++.

Anyways, I'm trying to compile my raytracer with g++, and I get this error:

In file included from engine.cpp:10:0:
objects.cpp: In function ‘Vector Trace(Ray&, std::vector<Object*>&, float, int)’:
objects.cpp:97:30: error: conversion from ‘Object*’ to non-scalar type ‘Object’ requested
objects.cpp:110:29: error: conversion from ‘Object*’ to non-scalar type ‘Object’ requested
engine.cpp: In function ‘int main(int, char**)’:
engine.cpp:36:55: error: invalid initialization of non-const reference of type ‘std::vector<Object*>&’ from an rvalue of type ‘std::vector<Object*>*’
objects.cpp:86:8: error: in passing argument 2 of ‘Vector Trace(Ray&, std::vector<Object*>&, float, int)’

I know all of these errors revolve around my objects variable, as I'm not really sure how to make arrays of objects and use it properly from within functions.

Here's part of my main():

vector<Object*> objects;

Sphere sphere = Sphere();
sphere.pos = Vector(0, 0, 0);
sphere.radius = 1;
sphere.diffuse = Vector(1, 1, 1);

objects.push_back(&sphere);

And the deceleration of Trace():

Vector Trace(Ray &ray, vector<Object*> &objects, float roulette, int n = 0) {

Sphere is declared like so:

class Sphere: public Object {
  public:

I'm not really sure what to do, as I've tried tweaking just about everything about that vector<> thing!

EDIT

Here's line 97:

Object target = objects[i];

Upvotes: 1

Views: 3445

Answers (1)

Erik
Erik

Reputation: 91320

You didn't include the line that have problems.

In objects.cpp:97 you're doing something like this:

Object x = objects[0];

This won't work, as objects is a vector of Object *

Use e.g. one of these:

Object * x = objects[0]; // x points to the actual Object in your vector
Object x = *objects[0]; // x is a copy of the Object in your vector
Object & x = *objects[0]; // x is a reference to/alias of the actual Object in your vector

On the second error, you try to pass a vector<Object*> * where a vector<Object*> is expected. Don't pass &objects but rather just objects

Upvotes: 3

Related Questions