• Advertisement
Sign in to follow this  

c++, when to use pointers with get functions?

This topic is 4800 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I was wondering with get functions in classes, should I always make them pointers to the values? eg For a window class the 'hWnd' should i return it like HWND* getHWND(){return &hWnd;} And say other values like 'width', 'height' int* getWidth(){return &width;} As in one of my programs in an extreme case, I was using getWidth without a pointer and it seemed to slow down the program alot. I made it speed up by storing the int width, height in that current class's initialiser where i called the getWidth/Height only once. So should I always use pointers, or is there something wrong with doing that? Thanks

Share this post


Link to post
Share on other sites
Advertisement
If you're returning a pointer to a variable why is the variable not public in the first place? By returning the pointer you totally defeat the purpose of getter/setter functions. NEVER EVER RETURN A POINTER TO A PRIVATE OR PROTECTED VARIABLE WITH A GETTER!!! It reeks of poor design.

As for the speed impact, there is none when you compile with optimisations turned on. Having said that you usually notice the difference even with optimisations turned off. How were you testing the speed? Secondly, if anything changing to pointers will slow things down since you then have to dereference the pointer. But again, with optimisations on there'll be 0 performance hit.

Share this post


Link to post
Share on other sites
For values such as width, return a copy - return by value. Only return a pointer when the calling code might need to modify the variable. Obviously, you never want to return a private or protected member by pointer, because they should be modified via accessors that validate changes.

From an efficiency standpoint, you might want to return by pointer to reduce memory consumption. Keep in mind that returning a pointer to a locally allocated variable will yield an invalid pointer as the object goes out of scope, and that it is bad form and design to dynamically allocate memory withing a function and then expect the calling code to release it. Consequently, have calling code pass in an allocated object/buffer to be filled in such instances.

In short order, with the advent of references in C++, there is never a reason to return a value by pointer.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement