I lately talked with a friend about which language is the best and he told me that C++ doesn’t have Interfaces like Java.

Well, that’s no true, you can create Interfaces in C++ like this:

#include <iostream>

class IRenderable {
public:
    virtual ~IRenderable() {}
    virtual void Render() = 0;
};

class MyRendererableNode : public IRenderable {
public:
    virtual void Render() {
        std::cout << "Rendering stuff..." << std::endl;
    }
};

int main (int argc, char * const argv[]) {
    // IRenderable foo; <-- this is not allowed
    MyRendererableNode foo;
    foo.Render();
}

Don’t forget the virtual destructor, so the following code won’t do strange things:

IRenderable *foo = new MyRendererableNode();
foo->Render();
delete foo, foo = NULL;
  1. echsenkoenig (2011-02-05 02:14)

    I always thought that was basic knowledge, because we learned it during my first computer science course.Amazed greetings

  2. opeo (2011-02-05 03:56)

    class clonable{ virtual ~clonable() = 0{}};

  3. Ian (2011-02-05 04:39)

    Wouldn’t it also be appropriate to make IRenderable an abstract class and make its methods abstract as well? That would force you to implement all its methods in the base class and would prevent you from being able to instantiate an object for that class, both of which are characteristics of Java interfaces. Also, why is "IRenderable foo;" not allowed? Because it has no explicit constructor?

  4. joe (2011-02-05 10:25)

    C++ auto generates default constructors. It’s not possible to instantiate IRenderable because it contains pure virtual methods, that have to be implemented in their derived classes.virtual void Render() = 0;

Add your comment now