What's the convention for naming functions in C++?
I come from the Java environment so I usually name something like:
myFunction(...) {
}
I've seen mixed code in C++,
myFunction(....)
MyFunction(....)
Myfunction(....)
What's the correct way?
Also, is it the same for a class method as well as a non-class method?
Personally, I prefer
thisStyle
toThisStyle
for functions. This is really for personal taste, probably Java-influenced, but I quite like functions and classes to look different.If I had to argue for it, though, I'd say that the distinction is slightly more than just aesthetic. It saves a tiny bit of thought when you come across function-style construction of a temporary. Against that, you can argue that it doesn't actually matter whether
Foo(1,2,3)
is a function call or not - if it is a constructor, then it acts exactly like a function returning a Foo by value anyway.The convention also avoids the function-with-same-name-as-a-class-is-not-an-error fiasco that C++ inherits because C has a separate tag namespace:
Bar is, after all, both a noun and a verb, so could reasonably be defined as a class in one place and a function in another. Obviously there are better ways to avoid the clash, such as proper use of namespaces. So as I say, really it's just because I prefer the look of functions with lower-case initials rather than because it's actually necessary to distinguish them from from classes.
Unlike Java, C++ doesn't have a "standard style". Pretty much very company I've ever worked at has its own C++ coding style, and most open source projects have their own styles too. A few coding conventions you might want to look at:
It's interesting to note that C++ coding standards often specify which parts of the language not to use. For example, the Google C++ Style Guide says "We do not use C++ exceptions". Almost everywhere I've worked has prohibited certain parts of C++. (One place I worked basically said, "program in C, but
new
anddelete
are okay"!)It all depends on your definition of correct. There are many ways in which you can evaluate your coding style. Readability is an important one (for me). That is why I would use the
my_function
way of writing function names and variable names.If you look at the standard libraries the pattern generally is my_function, but every person does seem to have their own way :-/
I think its a matter of preference, although i prefer
myFunction(...)
There isn't a 'correct way'. They're all syntactically correct, though there are some conventions. You could follow the Google style guide, although there are others out there.
From said guide: