In Java, all methods, variables, named constants, etc. must be members of a class. In C++, all of these are allowed to be members of a class, but they are not required to be. Specifically, they can be declared at global scope and not associated with any class.
As an example, the following is a complete and valid C++ program, but would not be valid in Java
because none of count
, printGreeting
, nor main
is a member
of a class:
#include <iostream> int count = 0; // an external integer; neither a class nor an instance variable void printGreeting() // an external function; neither a class nor an instance method { std::cout << "Greetings, earthling!"; std::cout << " (This is greeting number " << (++count) << ")\n"; } int main() { printGreeting(); printGreeting(); printGreeting(); return 0; }
Output:
Greetings, earthling! (This is greeting number 1) Greetings, earthling! (This is greeting number 2) Greetings, earthling! (This is greeting number 3)
count
and printGreeting
can be especially
problematic because – among other things – they violate
the principle of Information Hiding, and they invite name conflicts caused when independent
source code files declare and use identifiers of their own using the same names.main
is the only identifer that
must be declared as a function at global scope and outside all namespaces.