Previous section To contents Next section

6.4 Pike and object orientation

In most object oriented languages there is a way to write functions outside of all classes. Some readers might think this is what we have been doing until now. However, in Pike, all functions have to reside within a program. When you write a simple script in Pike, the file is first compiled into a program then cloned and then main() is called in that clone. All this is done by the master object, which is compiled and cloned before before all other objects. What the master object actually does is:
program scriptclass=compile_file(argv[0]); // Load script
object script=scriptclass(); // clone script
int ret=script->main(sizeof(argv), argv); // call main()
Similarly, if you want to load another file and call functions in it, you can do it with compile_file(), or you can use the cast operator and cast the filename to a string. You can also use the module system, which we will discuss further in the next chapter.

If you don't want to put each program in a separate file, you can use the class keyword to write all your classes in one file. We have already seen an example how this in chapter 4 "Data types", but let's go over it in more detail. The syntax looks like this:

class class_name {
This construction can be used almost anywhere within a normal program. It can be used outside all functions, but it can also be used as an expression in which case the defined class will be returned. In this case you may also leave out the class_name and leave the class unnamed. The class definition is simply the functions and programs you want to add to the class.

To make it easier to program, defining a class is also to define a constant with that name. Essentially, these two lines of code do the same thing:

class foo {};
constant foo = class {};
Because classes are defined as constants, it is possible to use a class defined inside classes you define later, like this:
class foo
    int test() { return 17; }

class bar
    program test2() { return foo; }

Previous section To contents Next section