V
Victor Bazarov
Looza said:I have defined a class which takes a string, does some manipulation on it
and returns a character. It's a simple kind of check procedure to ensure a
code has been entered correctly. It is defined as so:
class cLotCheck
{
private:
// some private stuff
char GetCheckChar(const std::string& s);
public:
cLotCheck();
char operator()(const std::string& s) {
return GetCheckChar(s);
}
};
Is it valid C++ to use it as so:
cLotCheck check;
char ch = check("stringvalue");
Absolutely!
The code obviously works, but I was unsure if it is safe to use like this,
Safe? [What's that all talk about safety today?] How could it be unsafe?
If it compiles and does what you need, why do you still have a problem?
or if there is a preferred way (originally it was written as a function, but
I wanted to put it into a class for self-teaching purposes)
You wrote a functor. Congratulations. Now you know that it's possible to
write a class that kind of works like a function. It's a functor. There
are very good uses for functors in C++. You will learn more about those
as you study the standard library.
Victor