0

Just learning C++, encountered an issue that i'm not really sure why the following is the case.

Doesn't work

ChildObject in = myObject.getObjFromVector(0);
ChildObject out = myObject.getObjFromVector(1);
doSomething(in.property, out.property); // void doSomething(Thing &in, Thing &out)

where 
ChildObject& getObjFromVector(int index)

Works

process(myObject.getObjFromVector(0).property, myObject.getObjFromVector(1).property);

In case your wondering, though i don't think its relevant, Thing is Mat from opencv. This question however is about why the above works in one way but not the other.

Interestingly Which is more performant, passing a method the entire object, or a property of that object? suggests that both should work, or at least be acceptable. I'm definately doing something wrong though and this might be down to something in openCV i'm not aware off.

edit: I'm effectively carrying out some image manipulation on the .property value. like

process (Mat &src, Mat &out){
...
pyrDown(src, result, Size(src.cols / 2, src.rows / 2));
...

WHen its not working, i'm not seeing the pyrDown take effect.

Community
  • 1
  • 1
Emile
  • 11,451
  • 5
  • 50
  • 63
  • Does `getObjFromVector()` return a reference? If so, the problem may be object slicing (though I am not sure what _doesn't work_ means). – hmjd Jul 25 '12 at 15:42
  • ChildObject& getObjFromVector(int index) though what i don't understand is why the same method is used in the working example. – Emile Jul 25 '12 at 15:44
  • What types are the `Thing`s expected by doSomething? – juanchopanza Jul 25 '12 at 15:50

1 Answers1

1

This is possibly due to object slicing (I am not familiar with openCV). In the first example:

ChildObject in = myObject.getObjFromVector(0); 

a copy is made of object referred to by the return value of getObjFromVector() as in is of type ChildObject, not ChildObject&.

The second example passes the reference returned directly to the function so no object slicing occurs.

hmjd
  • 120,187
  • 20
  • 207
  • 252
  • Ha, i had tried that as well must have had something else wrong. Thanks that did the trick. – Emile Jul 25 '12 at 16:11