This is a kind of stupid simple question, I’m learning C++ and have the following class…
class Client
{
public:
Window getWindow() { return window; };
private:
Window window;
};
And what I’m wondering is will getWindow() return a reference to my private window object or a copy? Should I use a pointer here instead?
What’s killing me is that in Java the new keyword makes it very clear when and where objects are created, in cpp it’s much less clear, and my experience with C makes matters even worse.
Thanks, -Cody
Unless and until you explicitly state to return a reference it will return a copy. Please note, returning a pointer would not be a good idea at least in c++
TO return a reference, you have to add
&to the return typeNote, if you are concerned by the overhead of returning a value, you may be assured that all latest compilers does to some extent
return value optimization.Also, if you are using C++11, you can also take advantage of move semantics.