简体   繁体   中英

What are helper functions in C++?

I was trying to understand what "helper functions" are in C++ from "The C++ Programming Language" by Bjarne Stroustrup. But the book hasn't explained anything about it and the purpose of using it in classes. I tried searching for it on Web and found this<\/a> [note: dead link]. I have got the gist of it but still unclear about what is the real purpose of helper functions, when should I use them and on the whole, what are helper functions?

"

"helper function"<\/strong><\/em> is not a term that you would find in a standard, neither it has an exact definition... standard mentions "helper class"<\/em> or "helper template"<\/em> few times to refer to a class, which is not meant to be instantiated by end-users but it provides an useful functionality internally used within another class.

You can create helper functions meant to be used for many different kinds of purposes...

std::wstring s2ws(const std::string& str)
{
    int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
    std::wstring wstrTo( size_needed, 0 );
    MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
    return wstrTo;
}

There is a great definition of a helper function from the CppCoreGuidline<\/a> :

Placing them in the same namespace as the class makes their relationship to the class obvious and allows them to be found by argument dependent lookup.

An example could be the input validation function that you will be reusing in the entire main function. Let's say you have a program that asks for the user's age, since age is an integer > 0, you'll need to have a separate function that takes care of the "cin >> users_age;". If the input satisfies the condition statement then proceed, otherwise ask the user to re-enter their age.

This is just an example of "helper function". Correct me readers if I'm wrong. Thanks!

"Helper functions" are described in Bjarne Stroustrups book, and I was just reading about them yesterday. According to Stroustrup good design of a class should keep the number of functions implementing a class to a minimum. You dont want to have 50 functions in a class, according to Stroustrup. Instead you use "helper functions" that use the class interface (call the member functions). They could perhaps (not sure about this) be defined in a shared namespace to give meaning to their "relationship". You can find the paragraph in the book in chapter 9 section 9.7.5

"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM