Re: Return by reference
On Sun, 2014-02-09, Giuliano Bertoletti wrote:
Hello,
I've a classes like this:
class SubObject { ... };
class Object {
public:
SubObject sub;
};
class MyClass {
public:
Object obj;
public:
SubObject &GetSubObject() { return obj.sub; } // shortcut
};
which is the difference of calling?
==================
MyClass c;
SubObject &sub = c.GetSubObject();
SubObject sub = c.GetSubObject();
==================
It compiles both ways.
In practice I've an higher number of nested classes, so GetSubObject()
is actually a shortcut which digs deep into MyClass and retrieves the
item I need.
You might want to review that design to see if there is a smarter way
of doing it. You're saying you drill past three or more levels to get
that object, and that seems unusual. Perhaps your classes are too
much like dumb data containers, and you could change them to contain
more of the intelligence?
On the other hand, dumb data containers aren't always a bad idea ...
By the way, don't forget the third form:
const SubObject& sub = c.GetSubObject();
Here you're still at the mercy of whoever owns the object, but at
least you're promising not to modify it without informing the owner.
It's rather common to only need read access to something. This way
you can document it, and the code will IMO be significantly easier
to read.
/Jorgen
--
// Jorgen Grahn <grahn@ Oo o. . .
\X/ snipabacken.se> O o .