Methods without class

In our project I came across with a source file where there was a method that had no class. That method is called once directly from class A, and nowhere else. For me this seemed bit odd. Is there any reason to make C++ code like that. Code we make is embedded C++.
Last edited on
Are you asking why someone might make a function that isn't part of a class, or are you asking why is a function only being used once?
Last edited on
Yes, there are tons of reasons to have free-floating functions not attached to a class.

Consider the function ipow ... many people write this to raise a number (any type) to an integer power more efficiently than std::pow(). You might use it in a dozen classes if your code is math heavy; it belongs to none of them. You could wrap it in a class, but that is just clutter and if not careful overhead as well. It is a perfectly viable stand-alone function.

C++ is a hybrid language and there are times and places where procedural programming design is OK. Most of the time, OOP principles and design are superior, but when a stand alone routine is called for, use one.

Last edited on
> Is there any reason to make C++ code like that.

This article may be worth a read:
If you're writing a function that can be implemented as either a member or as a non-friend non-member, you should prefer to implement it as a non-member function. That decision increases class encapsulation. When you think encapsulation, you should think non-member functions. - Scott Meyers in Dr Dobbs
http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197
For the question of why a function is only being used once, or why have a function if it's only being used once: Even if a function is only used once, and is only one or two lines long, it can still help to put a name to what action is being done, as opposed it to being a comment that will get lost in the middle of another function.

It helps separate out the logic of that particular action from the logic of the rest of the function, for purposes of clarity to future readers.
Last edited on
Topic archived. No new replies allowed.