Interface Class
An interface is used to describe a behaviour, which is followed by all of the classes deriving from the interface. An interface class does not implement any functionality. It means that such a class contains only functions declaration. Interface class functions must be implemented by derived classes.
The interface is used to provide a polymorphism. It means that several classes can implement the same interface functions in different ways.
Interface Class#
The interface class is declared as any other class in UnigineScript. In the example, the abstract virtual function declaration is used.
class Interface {
// functions declaration
void update() = 0;
//...;
}
Any class that is inherited from the Interface class must contain an implementation for its functions. For example:
class Bar : Interface {
// implementation of the interface function for Bar
void update() {
log.message("Bar::update(): called\n");
}
};
class Baz : Interface {
// implementation of the interface function for Baz
void update() {
log.message("Baz::update(): called\n");
}
};
Example
Let's suppose that there is an interface class, which describes an object:
class Interface {
void update() = 0;
}
Bar and Baz classes decribe two different objects. This classes are inherited from the Interface class, and also the Bar class is derived from the Foo class.
class Foo {
void foo() = 0;
};
class Bar : Foo, Interface {
void update() {
log.message("Bar::update(): called\n");
}
};
class Baz : Interface {
void update() {
log.message("Baz::update(): called\n");
}
};
The interface is used to iterate objects of different types that implement that interface. So, you can create an array of the objects and update them all.
Interface interfaces[0];
interfaces.append(new Bar());
interfaces.append(new Baz());
foreach(Interface i; interfaces) {
i.update();
}
Bar::update(): called
Baz::update(): called
Abstract virtual function declaration#
A virtual function is a function, which can be overridden in a derived class.
You can declare the virtual function the following way (C++ style):
class Foo {
void foo() = 0;
};