Example 1 introduced a class "Hello" which has a method "sayHello" that prints the fixed string "Hello, World!" Example 2 extends the "Hello" class so that clients can customize the output from the method "sayHello".
Class "Hello" is extended by adding an attribute that we call "msg". Declaring an attribute is equivalent to defining "get" and "set" methods. For example, specifying:
attribute string msg;
is equivalent to defining the two methods:
string _get_msg(); void _set_msg(in string msg);
Thus, for convenience, an attribute can be used (rather than an instance variable) in order to use the automatically defined "get" and "set" methods without having to write their method procedures. The new interface specification for "Hello" that results from adding attribute "msg" to the "Hello" class is as follows (with some comment lines omitted):
#include <somobj.idl> interface Hello : SOMObject { void sayHello(); attribute string msg; //# This is equivalent to defining the methods: //# string _get_msg(); //# void _set_msg(string msg); };
Customize the implementation file by modifying the print statement in the "sayHello" method procedure. This example prints the contents of the "msg" attribute (which must be initialized in the client program) by invoking the "_get_msg" method. Notice that, because the "_get_msg" method name begins with an underscore, the method is invoked with two leading underscores (for C only).
SOM_Scope void SOMLINK sayHello(Hello somSelf, Environment *ev) { /* HelloData *somThis = HelloGetData(somSelf); */ HelloMethodDebug("Hello", "sayHello"); printf("%s\n", __get_msg(somSelf, ev)); /* for C++, use somSelf->_get_msg(ev); */ }
This implementation assumes that "_set_msg" has been invoked to initialize the "msg" attribute before the "_get_msg" method is invoked by the "sayHello" method. This initialization can be done within the client program.
Modify the client program so that the "_set_msg" method is invoked to initialize the "msg" attribute before the "sayHello" method is invoked. Notice that, because the "_set_msg" method name begins with an underscore, the C client program invokes the method with two leading underscores.
For C programmers:
#include <hello.h> int main(int argc, char *argv[]) { Hello obj; obj = HelloNew(); /* Set the msg text */ __set_msg(obj, somGetGlobalEnvironment(), "Hello World Again"); /* Execute the "sayHello" method */ _sayHello(obj, somGetGlobalEnvironment()); _somFree(obj); return (0); }
For C++ programmers:
#include <hello.xh> int main(int argc, char *argv[]) { Hello *obj; obj = new Hello; /* Set the msg text */ obj->_set_msg(somGetGlobalEnvironment(), "Hello World Again"); /* Execute the "sayHello" method */ obj->sayHello(somGetGlobalEnvironment()); obj->somFree(); return (0); }
> hello Hello World Again
The next example extends the "Hello" class to override (redefine) one of the methods it inherits from its parent class, SOMObject.