0

I have a virtual method that returns a const reference to object. In one of derived classes I need to return a value. Is it possible to return a copy when using const reference return type?

Here is what I'm trying to do (simplified code because it is more complex):

const Object& method(){
  Object object;
  //...
  return object; //Wrong, returning reference to local variable.
}

I tried to use static value in that way:

const Object& method(){
  static Object object;
  object = Object();
  //...
  return object;
}

It is easiest solution but not very elegant.

Ava
  • 818
  • 10
  • 18
  • 5
    Sounds like an [XY problem](http://xyproblem.info/). – PaulMcKenzie Mar 31 '19 at 14:45
  • 1
    What's the rationale for the virtual function to return a reference? – StoryTeller - Unslander Monica Mar 31 '19 at 14:47
  • Is this a case where in some classes that share this interface you return a const reference to a member of the class and in this particular class, all instances share the same value? If so, a class static is probably appropriate. – David Schwartz Mar 31 '19 at 14:55
  • No, they do not share the same value. I've just read related question to this one https://stackoverflow.com/questions/6465447/is-it-ok-to-return-reference-from-pure-virtual-function. I didn't know that it is a bad design. The reason for returning by reference is that my object may be large (it contains an array) and I'm wondering if returning by value isn't a bad idea here. – Ava Mar 31 '19 at 15:01
  • 3
    Don't try to optimize for the compiler. Write [NRVO](https://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization) friendly code and be done with it. You fell into a trap by trying to optimize prematurely. – StoryTeller - Unslander Monica Mar 31 '19 at 15:03

1 Answers1

1

I have a virtual method that returns a const reference to object. In one of derived classes I need to return a value.

Solution: Change your design so that

  • The return type is not a reference or
  • Derived class doesn't need to return a value.

Otherwise the derived class doesn't conform to the interface that it inherits.

Can I return copy as a reference?

You can return a reference to an object that is a copy of another object. But you need to store the object - whose reference you return - somewhere.

eerorika
  • 232,697
  • 12
  • 197
  • 326