# Programming Language Concepts Using C and C++/Object Orientation

Success of a business depends on its competitiveness, which generally translates to offering easily-upgradeable, high quality products at a moderate price in a reasonable time. This is not any different in software industry: the faster, the less costly, the more flexible the better. Key to achieving this is avoidance of doing the same thing more than once: reuse.
Reusing code, for instance, will save us the development time of the reused module; it will generally lead to faster and/or smaller code because it has been profiled and fine tuned; it will be more reliable because it has been debugged.
In a procedural programming language such as C or Pascal, where subprogram is the natural unit of reuse, composition is the way to achieve reuse: One builds complex subprograms by composing it from simpler ones. Object-oriented programming languages offer an alternative: inheritance. In addition to composing objects from sub-objects, one can use inheritance to derive a new class from an existing one, which means objects of the new class will contain a sub-object of the base one. In other words, composition and inheritance basically boil down to the same thing. The difference lies in the agent that carries out the process: programmer and compiler, respectively.
In this chapter, a very simplistic simulation of object-orientation—with hopes of giving an insight—is provided in C. While perusing through the code keep in mind that this should not be taken as an authoritative source. There is certainly much more to it than is offered in this code.
Additionally, static checker, Splint, is introduced. It can be utilized to check source code for semantic errors, such as memory leaks, infinite loops, use of uninitialized data, and so on. Such a tool and the compiler can be used in tandem to make C a safer programming language.

## Modules
### Superclass

Header files ending with the _Private suffix contain information that normally should not have been revealed to the user of a module. This apparent mistake is due to the compilation model of C [and C++], which dictates that in order to define a variable a compiler must have access to the definition of relevant types. That doesn’t hurt much if you use pointers to structure instead of plain structures. However, inheritance requires composing objects from sub-objects, which means the derived type needs to have access to the structure of the base type. Now, it is very likely that implementers of the base type and the derived type are different [groups of] programmers. There must be a way to transmit the required information between these parties. The only way this can be done in C is through placing the type definitions in a header file, which is what we do in the files whose names end with the _Private suffix.
Next structure defines the members of an Employee object. Among these are two pointers-to-function, which can be made to point to different locations in the code segment. In other words different Employee objects can have different values in these pointers, which would mean they can react differently to the same requests. In our case, we will say that all Employees get a salary and a bonus, calculation method of which depend on whether a particular Employee is in fact an Engineer or a Manager.
Note that we include details of the structure in the header file, which is against our usual practice of deferring to the implementation file. This could still be done in such a manner by turning the structure definition (struct _EMPLOYEE) into a pointer to an incomplete type. However, it would not have reflected the true nature of inheritance: inheritance is composition carried out by the compiler; an object of the subclass containsmdash;in addition to its own data members—a sub-object of the superclass.
C, in the name of improving performance, is a very permissive programming language. This usually means most of the bookkeeping stuff that is deferred to compilers in many other programming languages fall to the share of the programmer. That’s okay when the program is not big and/or the programmer is a competent one. She can take the initiative and skip some of the aforementioned stuff, which would generally mean faster and leaner code. Or ...
One way to deal with the ominous alternative is to use a tool that detects programming anomalies in the source code. One such tool is Splint, which statically checks C programs for potential security vulnerabilities and programming mistakes. Doing this may sometimes require annotating the source code. These annotations are stylized comments that start with /*@ and end with @*/. Following prototypes are examples to this.
/*@null@*/ before the return type indicates that the function may return—in addition to a pointer to some memory region—a NULL value. Such a possibility means a careless programmer may end up trying to use non-existent Employee objects. Something we would not like to see happening and our friend, Splint, will not let it happen. The programmer must either make sure the returned value is not NULL or put up with the complaints of Splint. For different ways of assuring Splint that the returned pointer will never be NULL, take a look at here.
The preceding paragraph is actually a rephrase of the "declare before use" rule we stated in the Sample C Programs chapter. The compiler is contented with declaration of identifiers and [in the case of external entities when the corresponding definition cannot be found in the current preprocessed file] defers the control for the existence of a corresponding definition to the linker, which will not let you use an undefined identifier. In other words, compiler-linker duo is responsible for ensuring undefined identifiers are not used. However, since the heap region is managed by the programmer—in other words, objects are dynamically allocated [defined] by the programmer—it is not possible for the compiler-linker duo, which complete their job before run-time and are therefore static in nature, to enforce this rule for objects allocated in the heap. Programmer must walk the extra mile! In a programming language such as Java, this translates to guarding against the relevant exception, whereas in C it means a check against NULL.
A complementary annotation is /*@notnull@*/, which states that related identifier cannot have NULL as its value. For instance, destruction can take place only when it is applied on an existing object, which implies the argument passed to the destructor function must be non-NULL. Using this as an assurance, Splint will not let you pass some variable that can possibly have NULL as its value.
As for the /*@reldef@*/ annotation, it is used to relax definition checking for the relevant declaration. Storage annotated as such is assumed to be defined when it is used; no error is reported if it is not defined before it is returned or passed as a parameter.
Definition: An object [that is, a memory region] is said to be defined if storage required for it has been allocated. An object is completely defined if all storage that may be reached from it is defined.
    typedef struct _STUDENT { char* name; int no; } *Student; ... Student std1 = (Student) malloc(sizeof(struct _STUDENT)); /* At this point, std1 is defined. However, it is not completely defined. */ std1->name = (char*) malloc(20); /* std1 is now completely defined. */
In our example, construction of an Employee-derived object—Engineer or Manager—is completed in two different constructor functions. After allocating memory in either one of Engineer_Create or Manager_Create, control is passed to Employee_Create to initialize certain fields. Initialization is later completed in the caller of Employee_Create. This means there will be uninitialized fields on entry to Employee_Create, which further implies there may be undefined fields.
The /*@in@*/ annotation is used to denote a parameter that corresponds to an input argument and therefore must be completely defined. In our case, successfully constructing an Employee-derived object guarantees its complete definition.
Note, unless otherwise specified, Splint assumes all unannotated references—storage reachable from global variables, arguments, and return values—to be completely defined. One can relax this requirement by turning impouts flag off.
An Employee object can exist only as a sub-object of another object. This containing object is passed as the first argument to our constructor-like function. If this argument value is NULL, which means there is no containing object, we return without creating an Employee object. After all the notion of an Employee is an abstract one and cannot be concretized.
However, the concept of an Engineer is a concrete one and we can therefore create its object, which in turn contains an Employee part. The following constructor-like function serves to make allocations and initializations for this part.
Following if statement is here to convince Splint about our awareness of the possibility of a NULL return value from malloc. Thanks to this control we will not be harassed by Splint’s annoying warnings.
In case you may be sure the result will never be NULL—or you simply don’t care—and you don’t want to write this code fragment you may turn this control off by annotating every use of this->name with /*@-nullpass@*/.
If the value returned by the following statement is assigned to a global variable the underlying memory region will be shared between this [global] variable and the actual parameter.
    ... Employee global_emp; void func(...) { ... global_emp = Employee_Create(receiver_obj, ...); /* global_emp and receiver_obj is sharing the same underlying object. */ ... } /* end of void func(...)
Considering the programmer may well forget this and go on to free it through the argument, Splint steps in to give us a warning. Not concerned about it, we remove the check by means of the /*@-temptrans@*/ flag.
Remember the object being destroyed may be anything that derives from Employee. That is, if needed, we can extend the definition of Employee and come up with a new type, such as Manager. How we extend the base type is however unknown to the base type itself. For this reason, our destructor-like function frees only those regions common to all Employees.
Returning the department an Engineer works in is no different than returning the department of a Manager. Same can be said about returning her name. Regardless of which type of Employee object we deal with—be that an Engineer, Manager, or even a type that is yet to be defined—the way the answer is provided will always be the same. Therefore, instead of duplicating this unchanging behavior in all modules, it’ll be wise to put such functionality in a central repository, which in our case happens to be the base type, Employee.
Thanks to this property of constant behavior—unlike salary and bonus calculation functions—these functions need not be invoked through pointers-to function, which implies binding of a call to either one of these functions can be performed before run-time.
Definition: A function call bound before run-time is said to be statically dispatched. For such a function, one can find out which function definition will be executed upon making the function call by simply reading the source code.

### Subclasses

An Engineer object is made up of two parts: its Employee sub-object and Engineer sub-object.
Note the following allocation reserves memory big enough to hold the Employee and Engineer sub-objects. Next thing we do, after memory allocation, is calling the constructor-like function of the base type, Employee_Create. Realize we do this before we initialize the Engineer-specific part of the object. The logic behind this is we may make use of certain information from the Employee part initialization for completing the Engineer-part initialization. However, it never happens the other way around: you don’t make use of Engineer-part information to complete the Employee-part initialization.
Now that Engineer is a concrete type we must provide implementations for salary and bonus calculations.
Note that the sole parameter in the function header is not used in the function body. A rather peculiar situation! Not surprisingly, Splint agrees with us on that and reports the potential problem source. Not caring a bit about the advice in this occasion, we get rid of the annoying warning by lifting the particular requirement. This is done by the /*@-paramuse@*/ flag.
Next annotation marks the type declaration as that of a Boolean type. Identifiers defined to belong to this type (Bool) can only be used—unless otherwise specified with some other annotation—in a Boolean context.
Indulging ourselves in some genuine C programming, we find ourselves using a Boolean value as an integer. That is not against the rules of C but Splint sees it as a potential bug and issues a warning. We should either take some corrective action, if there is any mistake, or relax the rules of Splint. We take the second path and state this using the /*@+boolint@*/ annotation.

## Test Program

Following annotation changes the special character that is used to mark the start and end of the stylized comments. From this point on, annotations will start with /*! and end with !*/.
print_tot_salary calculates the total payment [that is, bonus plus base salary] made to the Employees listed in the array passed to it. Each component of the array can be either an Engineer or a Manager. We cannot be sure of which component will belong to which group. But we can be certain about one thing: regardless of its real type, each component can be treated as an Employee. However, this has a limitation of its own: an Employee can answer questions that can be asked to all objects of the derived types. And indeed, that’s what we do: get the name of the Employee, calculate her salary and her bonus. We do not, for instance, inquire her discipline. Neither do we ask whether she accepts bribes or not. Because, the former is special to Engineers while the latter is special to Managers.
Next function call will be resolved before run-time—at link-time, to be exact—while the following two will be resolved at run-time. This is due to the fact that pointer values stored in calc_salary and calc_bonus are determined at the time of object creation, which happens during run-time.
Definition: Resolution of a function’s address at run-time is called dynamic dispatch. The ability of the same call resolving to different functions is called polymorphism.
Since Employee_GetName returns a possibly NULL value, which is later passed to printf, Splint raises an objection: How can you be so sure about printing the contents of a possibly non-existing character string? Well, I cannot but in this context it doesn’t seem very likely. So, I relax null-checking and let this one slip.
Note we cast each Engineer/Manager to an Employee. This will allow us to treat them the same way. Well, almost! The list of functions invoked using these objects will be limited to those that can be invoked using an Employee. However, the function invoked will depend on the type of the underlying object.
The Employee type here [that is, the type of the pointer variable] is called the static type—because it can be determined by reading the source code—whereas the type of the underlying object [that is, the type of the region pointed to by the pointer] is referred to as the dynamic type.
C++ equivalent of the next line is given below, which reflects the compiler's behind-the-scenes effort. Thanks to the inheritance relationship between Employee and Engineer, which is relayed to the compiler by means of the ':' operator, the cast is now implicit. Similarly, NULL argument meaning an Engineer object—not an object of a class inheriting from the Engineer class—is being created is not needed anymore. Finally, pointer values needed in the process of dynamic dispatch are gathered by the compiler—upon seeing the virtual keyword before the function signature—and inserted into a structure called vtable, which in turn is pointed to by an implicit field in the object being created, as a result of executing the compiler-synthesized code fragment.
    emps[0] = new Engineer("Eng 1", RESEARCH, EE);
Notice the different ways of convincing Splint about our awareness of the probable NULL value returned from the constructor function. All of these guarantee that a NULL pointer will never be dereferenced. In the first technique, we accomplish this by making an assertion that returned pointer is not null, which means the program will terminate upon receiving a NULL from Engineer_Create. Second and third techniques basically boil down to the same thing: by means of an if-statement the goal is achieved by explicitly checking the returned value against NULL.

### Running the Test Program

    splint -ID:/include Employee.c↵ # In Cygwin
    Splint 3.1.1 --- 02 May 2003
    Finished checking --- no warnings
    splint -ID:/include Engineer.c↵
    Splint 3.1.1 --- 02 May 2003
    Finished checking --- no warnings
    splint -ID:/include Manager.c↵
    Splint 3.1.1 --- 02 May 2003
    Finished checking --- no warnings
    splint -ID:/include Inheritance_Test.c↵
    Splint 3.1.1 --- 02 May 2003
    Finished checking --- no warnings
    gcc -ID:/include –o InheritanceTest.exe Inheritance_Test.c Employee.c Engineer.c Manager.c↵
    Inheritance_Test↵
    NAME SALARY BONUS TOTAL
    Eng 1 1000 300 1300
    Mng 1 1500 3000 4500
    Mng 2 1500 1000 2500
    Eng 2 1000 300 1300
Total payment: 9600

## Notes

* ↑ Reuse for the sake of reuse will not always save you precious resources. For this to be possible, it must be made part of the organization’s policies.
* ↑ Similar arguments can be made for reusing analysis and design documents.
* ↑ In this chapter, when we say inheritance we actually mean "inheritance together with polymorphism", which is what we understand from the natural application of the concept. However, as we will see in the Inheritance chapter, C++ allows inheritance to be used without polymorphism.
* ↑ In the case of multiple inheritance, derivation can be from multiple classes.
* ↑ We will have to rephrase this when we come to virtual inheritance in C++.
* ↑ ref!!!
* ↑ You can choose another character to play the role of “@”. For an example, check the test program.
* ↑ Unless otherwise told Splint assumes all pointer variables are annotated with /*@notnull@*/.
* ↑ A pointer with a NULL value is completely defined.
* ↑ s a matter of fact, name field will be undefined and therefore uninitialized.
* ↑ This is not the only way to convince Splint. For alternatives, check Inheritance_Test.c.
* ↑ Flags are supported to modify the behavior of Splint. Preceding a flag with + means it is on; preceding it with - means it is off.
* ↑ How can it possibly free regions that it doesn’t know about? After all, all Managers are also Employees, but all Employees are not Managers.
* ↑ This is another way of saying that messages sent to an object are filtered through its handle.
* ↑ In a larger program, doing so would not be the best of all choices. Making an assertion about the value of nm or checking it against NULL would be much wiser.
* ↑ Remember "The messages sent to an object is limited to ..."
* ↑ Read the "pointer variable" as "handle", "region pointed to by the pointer" as "object" and it will start to get more object-oriented.