Cody Smith
Cody Smith

Reputation: 2732

C++ passing member field

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

Upvotes: 0

Views: 100

Answers (2)

Abhijit
Abhijit

Reputation: 63737

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 type

class Client
{
public:
    Window& getWindow() { return window; };

private:
    Window window;
};

Note, 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.

Upvotes: 6

Alok Save
Alok Save

Reputation: 206546

By default C and C++ return by value.
It returns a copy of your member. A good compiler might optimize the extra call to copy constructor using N/RVO.

If you need to return your member itself(this is a bad idea) then you need to return a reference:

 Window& getWindow() 
      ^^^ 

Upvotes: 2

Related Questions