I’m not sure how to order my functions in C++. In C, I simply placed a function that uses another function below that function, as closely as possible – that’s pretty common. Like this:
void bar()
{
}
void foo()
{
bar();
}
However, in C++, there are several types of functions:
- Free functions
- Private member functions
- Public member functions
- Static member functions
I’m currently making my function order dependent on how they are ordered in the .hpp file, e.g.:
class Foo_bar {
public:
Foo_bar();
void foo();
private:
int some_member;
void bar();
But now, if the constructor uses foo() or bar(), these will be below the constructor in the source file, inconsistent with my usual ordering. I could of course reorder my header to take account of that:
class Foo_bar {
private:
int some_member;
void bar();
public:
void foo();
Foo_bar();
But I think that’s a mess.
Furthermore, in Java, the opposite to my first example seems to be common:
void foo()
{
bar();
}
void bar()
{
}
That’s probably due to the top-down thinking common in OOP, in contrast to the bottom-up thinking common in procedural/functional programming. However, with free functions that don’t have prototypes, this top-down style is not possible.
Is it even possible to order functions in C++ in a consistent way?
It’s possible. You have to use forward declaration.
Declare a function before defining it, and other functions will see it without problem even if they are defined before.
So, you should be able to do this in C++: