Previous section To contents Next section

6.6 Multiple inherit

You can inherit any number of programs in one program, you can even inherit the same thing more than once. If you do this you will get a separate set of functions and variables for each inherit. To access a specific function you need to name your inherits. Here is an example of named inherits:
inherit Stdio.File; // This inherit is named File
inherit Stdio.FILE; // This inherit is named FILE
inherit "hello_word"; // This inherit is named hello_world
inherit Stdio.File : test1; // This inherit is named test1
inherit "hello_world" : test2; // This inherit is named test2

void test()
{
    File::read(); // Read data from the first inherit
    FILE::read(); // Read data from the second inherit
    hello_world::main(0,({})); // Call main in the third inherit
    test1::read(); // Read data from the fourth inherit
    test2::main(0,({})); // Call main in the fifth inherit
    ::read(); // Read data from all inherits
}
As you can see it would be impossible to separate the different read and main functions without using inherit names. If you tried calling just read without any :: or inherit name in front of it Pike will call the last read defined, in this case it will call read in the fourth inherit.

If you leave the inherit name blank and just call ::read Pike will call all inherited read() functions. If there is more than one inherited read function the results will be returned in an array.

Let's look at another example:

#!/usr/local/bin/pike
                
inherit Stdio.File : input;
inherit Stdio.File : output;
                
int main(int argc, array(string) argv)
{
    output::create("stdout");
    for(int e=1;e<sizeof(argv);e++)
    {
        input::open(argv[e],"r");
        while(output::write(input::read(4096)) == 4096);
    }
}
This short piece of code works a lot like the UNIX command cat. It reads all the files given on the command line and writes them to stdout. As an example, I have inherited Stdio.File twice to show you that both files are usable from my program.


Previous section To contents Next section