Object-Oriented Programming Technology in C Language

Source: Internet
Author: User

The nesty framework provides the Object-Oriented Programming Technology in C. The following is a brief example to illustrate how it works.

Starting from the first simple example

Nobject is a base class of all object-oriented types in the nooc (nesty object-oriented C) framework. As an object-oriented programming interface, nobject provides object copying, object comparison, and object hashing, object stringization, as well as runtime type recognition, secure downward type conversion, and other functions. Therefore, all nooc objects must be derived from nobject. The following example defines an object my_class derived from nobject:

NOBJECT_PRED(MY_CLASS);NOBJECT_DEC(MY_CLASS, NOBJECT);struct tagMY_CLASS {NOBJECT_BASE(NOBJECT);};NOBJECT_IMP(MY_CLASS, NOBJECT);

Four key macros are used: nobject_pred is used for the pre-declaration object; nobject_dec is used for the actual declaration object, indicating the inheritance relationship between objects. From the code example, we can see that my_class inherits from nobject; because the object is simulated using the data structure of C, a data structure with the same name must be declared at the same time to store the data area of the object and the tag should be used as the prefix, for example, tagmy_class; because the Child class must contain the data of the parent class in the inheritance relationship, you must use the nobject_base macro class to declare the data zone of the parent class at the frontend of the data structure, in this example, the data zone of the parent class nobject is declared. The above part is the declaration of nobject, usually in the header file.

In addition to declaring nobject, you also need to use the macro nobject_imp to provide implementation for the object. The nobject_imp should be placed in the source file. Otherwise, an error not provided by the function will be thrown during compilation and connection. Nobject_imp matches with nobject_dec. The object inheritance relationship specified by nobject_imp must be consistent. For example, the parent class is nobject.

Once the object is declared, you can create and use the object, as shown in the following code:

// Create the object my_class OBJ = nNew (my_class); // verify its type nassert (nobjectclass (OBJ) = nclassof (my_class )); // verify the inheritance relationship nassert (Nisa (OBJ, nobject); // release the object nrelease (OBJ );

Because the object is generated through new, automatic garbage collection cannot be provided in the C language, you need to call the unified interface nrelease to release the object after using the object, as shown in the preceding example.

The following example creates a subclass my_sub that inherits from my_class:
NOBJECT_PRED(MY_SUB);NOBJECT_DEC(MY_SUB, MY_CLASS);struct tagMY_SUB {NOBJECT_BASE(MY_CLASS);};NOBJECT_IMP(MY_SUB, MY_CLASS);

Its syntax is exactly the same as the previous one. After my_sub is declared successfully, you can start to use it as follows:

My_class objsub = (my_class) nNew (my_sub); // verify the inheritance relationship nassert (Nisa (objsub, my_sub); // safely convert the data type to my_sub objsub_2 = ncast (objsub, my_sub); nassert (objsub_2! = NULL );

In this example, note that objsub is a pointer of the my_class type, but actually points to an instance of the my_sub type. In nooc rules, forced type conversion must be used for upward conversion. Next, it is worth noting that we also need to convert the objsub type down to the my_sub type to facilitate the operation of my_sub data and interfaces. In object-oriented rules, the base class (parent class) is usually used as the program interface, so the base class pointer can point to any instance derived from the base class, just like in the previous example, objsub can point to any instance of the class derived from my_class. to implement effective downward conversion, you need to call the ncast method to achieve dynamic conversion, ncast verifies the class hierarchy of the pointer instance. In the preceding example, only one instance of my_sub is returned for objsub. Otherwise, a null pointer is returned.

As in the previous example, objects must be released after use:

// Release the object nrelease (objsub );

In the following example, you can create classes with interfaces and data to implement more difficult details, add data to types, add virtual interfaces to types, and bind virtual interfaces to types, and constructor.

// xxx.hNOBJECT_PRED(MY_CLASS);NOBJECT_DEC(MY_CLASS, NOBJECT,NINT (*GetValue)(MY_CLASS InObj););struct tagMY_CLASS {NOBJECT_BASE(NOBJECT);NINT Value;};NINLINE NINT MyClassGetValue(MY_CLASS InObj) { return NOBJECT_VCALL(InObj, MY_CLASS, GetValue)(InObj); }// xxx.cvoid MyClassCtor(MY_CLASS InObj) {InObj->Value = 0;}NINT __MyClassGetValue__(MY_CLASS InObj) {return InObj->Value;}NOBJECT_IMP(MY_CLASS, NOBJECT,NCTOR_BIND(MyClassCtor)NVCALL_BIND(MY_CLASS, GetValue, __MyClassGetValue__));

Note that the annotations in the above example indicate that the two parts of the Code are in the header file and the source file respectively. In the above example, a function pointer is inserted at the end of the nobect_dec declaration to define getvallue, getvalue is used as a virtual interface of my_class. Note that in the Declaration in the previous section, nobject_dec only describes the inheritance relationship. In this section, a function declaration is added, this uses the macro variable parameter feature of c99. In the preceding example, the value of the data member is added to the tagmy_class statement. Now, go to the source file. myclassctor will be used as the constructor of my_class. It will be called when nNew is called to create the my_class object. This function must be bound to the class implementation of my_class through the nctor_bind macro, as shown in the preceding example. _ Myclassgetvalue _ is the default Implementation of the Virtual Interface getvalue, which is bound to the class implementation through nvcall_bind. Nvcall_bind needs to know which type of the interface is defined, so that virtual tables of this type can be obtained before calling a virtual function. Therefore, nvcall_bind must first pass my_class as the parameter, because getvalue is defined in my_class. Second, you need to tell nvcall_bind which interface is to be bound, so you need to pass getvalue, and finally pass the getvalue implementation _ myclassgetvalue __. Because _ myclassgetvalue _ is only an implementation, we all know from the characteristics of polymorphism that virtual interfaces can be overwritten, therefore, _ myclassgetvalue _ should not be exposed to the user through the header file. Adding double underscores _ In the definition indicates that this is a "protected" method. Now we use the actual example my_class:

MY_CLASS Obj = NNEW(MY_CLASS);NASSERT(Obj->Value == 5);

In the preceding example, calling nNew to create my_class triggers the constructor of my_class and initializes the value to 5. Next, we use the nobject_vcall macro to call the Virtual Interface defined by my_class.

NINT Val = NOBJECT_VCALL(Obj, NOBJECT, GetValue)(Obj);NASSERT(Val == 5);

Nobject_vcall contains two parts (observe the parentheses). The first part of nobject_vcall (OBJ, nobject, getvalue) is used to obtain the address of the virtual function. In an object-oriented instance, the instance is bound to the type of the relevant class (class type), so you need to pass the OBJ instance to obtain the OBJ class type information (that is, nclass ). With the class type, you need to obtain the virtual table. The second parameter is passed to my_class to tell nobject_vcall. I want to locate the virtual table of my_class, the last getvalue parameter tells me which function in the current virtual table needs to be called. After the virtual function pointer is returned as the power amplifier, the actual function is also called through the function pointer, from the nint
(* Getvalue) (my_class inobj);, we know that getvalue accepts a my_class instance as a parameter. If you find that the above example is difficult to understand, the following steps are taken:

typedef NINT (*NPfnMyClassGetValue)(MY_CLASS InObj);NPfnMyClassGetValue FnGetValue = NOBJECT_VCALL(Obj, MY_CLASS, GetValue);NINT Val = FnGetValue(Obj);

In fact, nobject_vcall is a very difficult interface (I hope to make it simpler), but to facilitate the call, you can use macros or Inline (c99) it is convenient and not difficult to encapsulate nobject_vcall at a time. For example, in the above example, we can define a virtual call interface for my_class, for example:

// For inline use, c99 must support ninline nint myclassgetvalue (my_class inobj) {return nobject_vcall (inobj, my_class, getvalue) (inobj );} // or the macro packaging result depends on how you use # define myclassgetvalue (inobj) nobject_vcall (inobj, my_class, getvalue) (inobj)

After encapsulation, the call to the virtual function is simplified to the following example:

NINT Val = MyClassGetValue(Obj);NASSERT(Val == 5);

Overwrite the Virtual Interface and then implement the object-oriented ghost weapon, that is, the runtime binding (or polymorphism ). The polymorphism mechanism provides the function to overwrite virtual functions, which is the core of object-oriented and can make different types of objects have different behaviors, this just simulates the fact that most similar things have different properties in some aspects. Therefore, the following example overwrites the Virtual Interface of my_class in the definition of my_sub so that it executes the behavior defined by my_sub.

NOBJECT_PRED(MY_SUB);NOBJECT_DEC(MY_SUB, MY_CLASS);struct tagMY_SUB {NOBJECT_BASE(MY_CLASS);NINT SubValue;};void MySubCtor(MY_SUB InObj) {InObj->SubValue = 2;}NINT __MySubGetValue__(MY_CLASS InObj) {MY_SUB Obj = (MY_SUB)InObj;return Obj->SubValue;}NOBJECT_IMP(MY_SUB, MY_CLASS,NCTOR_BIND(MySubCtor)NVCALL_BIND(MY_CLASS, GetValue, __MySubGetValue__));

The syntax used is exactly the same as before. The only thing worth noting is that the getvalue is rebound in the nobject_imp Implementation of my_sub. Therefore, when you call nNew to create a my_sub object and call getvalue, _ mysubgetvalue __is executed instead of _ myclassgetvalue __. So far, this is the most important technology in nooc. Another point to note is that my_sub's constructor initializes subvalue to 2, but my_sub's base class my_class also defines the corresponding constructor, when nNew is called to create an instance of my_sub, the constructor of my_class and my_sub will be called separately. The Calling sequence is the same as that of the C ++ constructor. To verify my statement, see the following example:

My_class objsub = (my_class) nNew (my_sub); // access my_class.valuenassert (objsub-> value = 5); my_sub objsub_2 = ncast (objsub, my_sub ); // access my_sub.subvaluenassert (objsub_2-> subvalue = 2 );

So far, I have introduced the most core nooc functions. For most people, these examples are not enough to illustrate the power of nooc. Therefore, I have written two unit tests in the test project: test_shooter_game and test_object_shooter_game (check test_shooter_game.cpp and test_object_shooter_game.cpp ). The former uses the C ++ language to develop a framework for a shooting game, which includes various C ++ object-oriented technologies used in actual situations, then in test_object_shooter_game, I use nooc to re-implement the entire framework. In fact, it proves that the two are completely consistent. However, nooc also has its shortcomings. For example, the interface is not user-friendly and I have to admit it. However, with so many restrictions on the C language, this is already the simplest mode I can develop, if you have better suggestions, contact me. OOC (Object-Oriented C language programming) is a very interesting topic. A foreign author once wrote an article titled object-oriented.
Programming with ANSI-C. If you are interested, you can refer to it. If you search for OOC under sourceforge.net, there will also be a lot of open-source projects, if you are interested, you can compare the differences between other implementations and nooc implementations. For the nesty download site, click the open link.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.