Partners: KDAB Whole Tomato Software CppDepend

25 April 2012

Non-meber, non-friend (functions)

cpp
In Effective C++ (3rd Edition) by Scott Meyers item 23 points that:
"Using non-member and non-friend functions (as a part of the interface of a class) improves its data encapsulation".
Let us look at some example:
class Renderer {
private: 
    some stuff...

public:
    drawTriangles();
    setRenderState();
};
void renderObjects(Renderer r, array of Objects) {
    foreach obj in Objects {
        r.setRenderState(obj.state, ...);
        r.drawTriangles(obj.triangles, ...)
    }
}
In the above example, the method renderObjects cannot access private stuff in the Renderer class and, that is why, it does not change data encapsulation level of the class. If we declared this function as a public member, then the number of methods/functions that have access to private members would increase.
The main reason for having such free function is that it is safe in case of changes. You can update internal implementation of the Renderer, but as long as you do not touch the interface, the free function (renderObjects) will work as expected.
You can go further and use namespaces to "modularize" the code. For instance, you can create namespace "RenderUtils" where methods like renderObjects will be placed.

Get my free ebook about C++17!

More than 50 pages about the new Language Standard.

C++17 in detail, by Bartlomiej Filipek

© 2017, Bartlomiej Filipek, Blogger platform
Any opinions expressed herein are in no way representative of those of my employers.
This site contains ads or referral links, which provide me with a commission. Thank you for your understanding.