2007-04-15

C++ Interfaces

Read up on how interfaces are implemented in C++. Apparently C++ doesn’t really implement them, at least not in the same way that VB.NET, C#.NET and (from what I remember) Java do.

Creating an interface in C++ means creating an “abstract base class”, or a class that cannot be instantiated. Creating such a class is easy - just make at least one of the methods a “pure virtual function”, like this:


Class MyBaseClass {
public:
    virtual void doSomething() = 0;
}

The method is made virtual by prefixing it with the “virtual” keyword (obviously enough). It is made a pure virtual function by adding “= 0” to the end of the declaration.

We can then create classes that inherit from this base class and implement the doSomething() method:


Class MyClass1 : public MyBaseClass {
public:
    void doSomething() {
        cout << "Doing something";
    }
}

Class MyClass2 : public MyBaseClass {
public:
    void doSomething() {
        cout << "Doing something else";
    }
}

We can even make a vector of the base class, yet insert the derived classes into it:


vector<MyBaseClass*> myVector;
MyClass1 *classInstance1 = new MyClass1();
MyClass2 *classInstance2 = new MyClass2();

myVector.push_back(classInstance1);
myVector.push_back(classInstance2);

This is known as “run-time polymorphism”, or “late-binding”. The problem with this is that the type conversions are, as the name suggests, done in run-time instead of at compile-time. Doing anything at run-time will incur a performance hit.

That way of handling multiple enemy types is out, then. Bah.