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)

Comments

  1. While such global identifiers are valid, their use should generally be minimized – preferably avoided – when developing object-oriented programming solutions as we will be doing in this course. External symbols like 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.
  2. What is the significance of the "std::" prefix we have been seeing on cout and cin? This refers to a "namespace". We will study C++ namespaces later, but for now, they are very roughly analogous to the Java package. They can be used to help with name scoping issues in general. Identifiers that are not members of any class can be placed in a namespace, thus minimizing the potential for name conflict problems for such identifiers. In addition to variables and functions, classes can be defined in namespaces for the same reason. For example, the C++ system defines the "std" namespace, inside of which the classes istream, ostream, ifstream, and ofstream are defined along with the identifiers cin, cout, and cerr, some of which we saw in the previous Keyboard/Screen I/O section. When we write, for example:
    std::cout << "Greetings, earthling!";
    we are telling the C++ runtime system to write the greeting string to the "cout" variable defined inside the "std" namespace.
  3. The special identifier main is the only identifer that must be declared as a function at global scope and outside all namespaces.