tags:

views:

105

answers:

4

In C++ one can have a 'GLOBAL FUNCTION', which means it does not belong to any class. I wondered if that isn't just a violation of the basic principles of OOP?

What would be the difference with using a global function or function that is static in a class? I'm thinking the latter is more OOP oriented. But I may be wrong however...

Does it not make it harder when writing a multithreaded applicaton?

+1  A: 

C++ facilitates many programming paradigms: structured, OOP, functional.

It makes no sense to choose for an OO approach for a small (hello world-style) program.

It makes no sense to use a structured approach for a modular program.

Next to that, static class functions are just better organized than 'free' functions; on top of that, they have access to an object's private variables - better encapsulation.

xtofl
I agree. C++ gives you freedom to choose the best aproach. I think that a programming language, first of all, should help to solve problems as efficient as possible.
pcent
+1  A: 

Static methods are able to access private static fields on the class they're in, but that's about the only difference from global functions.

Global functions are there because C++ is roughly a superset of C, and C has global functions. C can be used for both OOP and non-OOP programming.

And, frankly, does it really make a difference whether you type std::Math::max or std::max?

Matti Virkkunen
+4  A: 

A static function inside a class is as OO as a global function inside a module. The thing is in JAVA, you don't have the choice.

In C++, you can encapsulate your global functions inside namespaces, you don't need a dummy class to do this. This way you have modularity.

So of course you can put functions outside namespaces this way you have really global functions. But that's not very different from a JAVA kitchen sink class with a bunch of static functions. It's also bad code, but can be just ok for small projects :)

Also in C++ you have a lot of choices to have "global" function that actually are linked to a class, as operator functions, that may be for instance friends of a class.

EDIT As for multithreading, you have to worry about global variables, not functions.

Nikko
+1 for mentioning the `namespace` option.
xtofl
+1  A: 

Totally agree with other answers and i want to add my advice. Static functions and static methods are almost same things and abusing them can lead to poor oo design. If you want to keep your object model clean you should use static functions/methods only if:

  • they do not produce result that depends on state of object
  • they do not change state of object
Andrey
+1 : good advice
neuro