The previous example showed how to override the method somPrintSelf, introduced by SOMObject. As mentioned in that example, somPrintSelf should generally be overridden when implementing a new class. Another method introduced by SOMObject that should generally be overridden is somDefaultInit. The purpose of somDefaultInit is to provide a "default" initializer for the instance variables introduced by a class.
This example shows how to override somDefaultInit to give each "Hello" object's message an initial value when the object is first created. To learn more about initializers than shown in this example (including how to introduce new initializers that take arbitrary arguments, and how to explicitly invoke initializers) read Section 5.5, "Initializing and Uninitializing Objects," in Chapter 5, "Implementing Classes in SOM."
The overall process of overriding somDefaultInit is similar to that of the previous example. First, the IDL for "Hello" is modified. In addition to an override modifier, an init modifier is used to indicate that a stub procedure for an initialization method is desired (the stub procedures for initializers are different from those of normal methods).
#include <somobj.idl> interface Hello : SOMObject { void sayHello(); attribute string msg; #ifdef __SOMIDL__ implementation { //# Method Modifiers: somPrintSelf: override; somDefaultInit: override, init; }; #endif };
SOM_Scope void SOMLINK somDefaultInit(Hello somSelf, somInitCtrl *ctrl) { HelloData *somThis; /* set by BeginInitializer */ somInitCtrl globalCtrl; somBooleanVector myMask; HelloMethodDebug("Hello", "somDefaultInit"); Hello_BeginInitializer_somDefaultInit; Hello_Init_SOMObject_somDefaultInit(somSelf, ctrl); /* * local Hello initialization code added by programmer */ }
Here, the "msg" instance variable is set in the implementation template (rather than in the client program, as before). Thus, the "msg" is defined as part of the "Hello" object's initialization.
SOM_Scope void SOMLINK somDefaultInit(Hello somSelf, somInitCtrl *ctrl) { HelloData *somThis; /* set by BeginInitializer */ somInitCtrl globalCtrl; somBooleanVector myMask; HelloMethodDebug("Hello", "somDefaultInit"); Hello_BeginInitializer_somDefaultInit; Hello_Init_SOMObject_somDefaultInit(somSelf, ctrl); /* * local Hello initialization code added by programmer */ __set_msg(somSelf, "Initial Message"); }
#include <hello.h> main() { Hello h = HelloNew(); /* Execute the "somPrintSelf" method */ _somPrintSelf(h); }
> hello-- a Hello object at 200633A8 with msg: Initial Message