Virtual static functions ?

Jarrett Billingsley kb3ctd2 at yahoo.com
Sat Aug 12 21:31:05 PDT 2006


"nobody_" <spam at spam.spam> wrote in message 
news:ebm2t4$2cj4$1 at digitaldaemon.com...

> Thanks for the reply,
> It is probably because I do not program object orientated, as I still do 
> not know what virtual means
> sorry :)

Virtual methods are part of polymorphism, IMO just about the coolest part of 
OOP.

Basically, you have a base class.  It defines a method:

class A
{
    void fork()
    {
        writefln("in A!");
    }
}

If we call that method, it'll write "in A!".

Let's derive it, and override that method:

class B : A
{
    override void fork()
    {
        writefln("in B!");
    }
}

The 'override' keyword isn't necessary for this to work, but is a very 
helpful sort of contract when dealing with larger programs.

Now, if we create a B, and call fork, it'll write "in B!".  Not all that 
interesting.  But here's the cool part:

A a = new B();
a.fork();

What happened?  Since B derives from A, I can put a B into an A reference. 
But when I call a.fork(), what is printed?

"in B!"

This is because of virtual methods.  Basically, because we overrode fork() 
in the derived class, no matter how we access that class instance, calling 
fork() will _always_ call the fork defined in B.

The most common use for this is if you have some kind of generic base class, 
then derive from it to implement all the functionality for the various 
derived classes.  Then you can put a bunch of derived classes into one big 
list and call the methods, and the correct derived methods will be called.

class DirectoryEntry
{
    // needs to be overridden
    abstract void showMe();
}

class FileEntry : DirectoryEntry
{
    char[] name;

    override void showMe()
    {
        writefln("File: %s", name);
    }
}

class FolderEntry : DirectoryEntry
{
    char[] name;
    FileEntry[] files;

    override void showMe()
    {
        writefln("Folder: %s", name");

        foreach(FileEntry file; files)
            file.showMe();
    }
}

...

DirectoryEntry[] entries = myFileLib.listDir("C:\dmd");
foreach(DirectoryEntry e; entries)
    e.showMe();


-------------------

Since virtual function tables are associated with class instances and not 
with classes themselves, static methods (which are associated with the 
class) cannot be virtual.  They're really more like top-level functions 
which just happen to live in a class. 





More information about the Digitalmars-d-learn mailing list