Quick /

opC++ Features

opC++ Compiler

opC++ Language

opGames Company

Instance Reflection

Instance Reflection Tutorial

In this quick tutorial we show how you can use reflection on object instances. This allows you to learn about an object (names, types, modifiers, members, etc.), as well as find and manipulate data.

In opC++, you can use reflection on opclasses and opstructs. An opclass is a category introduced by the opC++ Standard Dialect. It is a step above the C++ class construct, and automatically adds serialization and reflection features.

First, let's first define a simple opclass we can use reflection with:

Here we've defined an opclass called ProgrammingLanguage with two data members, SupportsReflection and Keywords. We've also defined a method to print out all the keywords in an instance.

Now, let's use opC++ instance reflection - what we'll attempt to do is find the SupportsReflection member, then find the Keywords vector and add some data into it:

In the first part of the above example, we declare a ProgrammingLanguage instance and use opC++ reflection to see if it has a data member named "SupportsReflection". If a variable of this name does not exist in the instance, then the field will be NULL.

In the second part of example, we attempt to get access to the ProgrammingLanguage field Keywords. If we succeed, we obtain a pointer to the actual data of the ProgrammingLanguage instance using the field's get_value function.

If the type is incorrect in the get_value method, it will safely return NULL. If it's valid, we can add some keywords to the vector. Of course, since we know the names and types are correct, this will succeed.

The output for this small example is shown below:

We see that a member called SupportsReflection exists in the ProgrammingLanguage opclass. We can also see how we changed the data directly on a ProgrammingLanguage instance. In our example the Keywords vector is empty, but with the reflection code we added three keywords to it.

In this tutorial we've shown you how to use opC++ reflection to access a named field and get the data from it, given an object instance. We've shown you how you can extract data if you know the exact type that you're accessing.

There are even faster and more powerful ways to use reflection in opC++ through visitors and data accessors, covered in the next tutorial.

Project Files (VS 2005): InstanceReflection.zip

Recent Changes (All) | Edit SideBar Page last modified on December 11, 2007, at 09:43 PM Edit Page | Page History
Copyright 2010 opGames Inc.