开发者

c++ global functions and OOP?

开发者 https://www.devze.com 2023-01-02 12:21 出处:网络
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?

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 latt开发者_运维问答er is more OOP oriented. But I may be wrong however...

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


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.


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.


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?


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
0

精彩评论

暂无评论...
验证码 换一张
取 消