Sign in to follow this  
johnnyBravo

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

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this