Virtual Classes
What would happen if you could overwrite your nested classes...
![](https://eu-images.contentstack.com/v3/assets/blt740a130ae3c5d529/bltba62518415cda0e2/652fe6ddbc479f8697ef691f/default-cubic.png?width=1280&auto=webp&quality=95&format=jpg&disable=upscale)
Every programmer knows the benefits of polymorphism and virtual methods. But only few know about virtual classes (not to be mixed with virtual base classes from C++).
So what is a virtual class? It has its origins in BETA-Programming Language. Basically, it is a nested class (a class in a class), which can be overwritten. Just like a virtual method.
In a fictive C++ like language, an example would look similar to this:
class BaseGraph {
public:
virtual class Node {...};
virtual class Edge {... Node source, target; ...};
};
class ColoredGraph : public BaseGraph {
public:
// overwriting Node and adding the color property to it
virtual class Node {... Color color; ...};
};
Following things happen here:
all nested classes are declared as virtual (can be overwritten)
nested class Node ist overwritten in ColoredGraph
ColoredGraph::Node is a subclass of BaseGraph::Node
all existing references to Node in the context of the ColoredGraph get automatically bound to the overwritten class. Hence, ColoredGraph::Edge::source is a subtype of ColoredGraph::Node and it will have access to the color property. Note that Edge has not been changed at all!
Instantiation looks like this:
BaseGraph* g = new ColoredGraph;
g::Node* node = new g::Node;
The fancy things here are:
g::Node - Node as a property of the object g
late bound new operator - new g::Node will instantiate the Node class depending on the runtime type of g, in this case it will be ColoredGraph::Node.
This is so called family polymorphism (gbeta, Eric Ernst).
If you are interested in a bigger example demonstrating how virtual classes could be applied in the game-programming context, look at V. Gasiunas and I. Aracic. Dungeon: A Case Study of Feature-Oriented Programming with Virtual Classes. 2nd Workshop on Aspect-Oriented Product Line Engineering (AOPLE), Salzburg, Oct 2007.
Also an interesting thing: FeatureC++
I am really, really looking forward to see one day virtual classes being a part of the main-stream technology!
Read more about:
BlogsAbout the Author(s)
You May Also Like