Файл: Interfacing with C plus plus-programing communication with microcontrolers (K. Bentley, 2006).pdf

ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 14.06.2025

Просмотров: 3602

Скачиваний: 1

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.

66 4 THE OBJECT-ORIENTED APPROACH

derive the new Circles class from it. The derived class Circles is said to be a sub-class of the abstract class Shape and will inherit all its functions (and data if it had any). The Shape class does not have properties specific to a circle object such as centre and radius. These properties will be added as new member data to the derived class.

4.9 Multiple Inheritance

It is also possible for a derived class to have more than one base class. In this case the derived class will inherit all the member data and member functions of all the base classes. For example, we can have a base class named Colours, which allows us to set foreground and background colours, choose fill patterns, and carry out filling. We can use the Shape class and the Colours class to derive our new object class Circles (as shown in Figure 4-6). Now the Circles class can be made to show colourful circles on the screen!

Shape

Colours

(Abstract Base Class)

(Base Class)

Circles

Figure 4-6 Multiple inheritance.

4.10 Polymorphism

In principle, object-oriented concepts are profoundly based on the mechanisms of encapsulation, inheritance, and polymorphism. Polymorphism is a more complex concept than the concepts of encapsulation and inheritance which have already been briefly explained.

As applied to object-oriented programming, polymorphism means the existence of a function with the same name, same return value type, same number of parameters and the same type of parameters in a number of classes of the same hierarchy. The bodies of the functions will differ to suit the requirements for each class. It is not essential for every object in the hierarchy to have this function. Furthermore, there can be any number of polymorph functions in a given hierarchy. Polymorphism allows a common interface for related actions. The most powerful feature of object-oriented programming is associated with polymorphism of virtual functions (discussed in Chapter 8).

4 THE OBJECT-ORIENTED APPROACH 67

Let us consider an example of polymorph functions. Since a polymorph function is the ‘same’ function throughout the hierarchy, one would imagine that it carries out the same task in each class. Going back to our graphics example, we can consider Show to be a polymorph function. The function Show is in the Shape class, in the Circles class, in the Squares class, and so forth. Another polymorph function is Hide. Suppose the Show function makes the object visible on the screen. If we are using the Show function with a circle object, it will show a circle. If it is used with a square object, it will show a square. Therefore, although the function name is the same, it operates in a context-sensitive manner according to the type of object it is working with.

Polymorphism is the key to harnessing the great benefits of virtual functions. It is possible for a programmer to use a virtual function in a program without knowing which object it will be used with at run-time (when the program is executing). The program will be written generically to suit all classes of the hierarchy. The programmer does not need to write the complex logic for selecting the correct function to suit the object chosen by the user at run-time. This task is passed on to the compiler and linker, simplifying the programming task immensely. This is of most benefit for programs with large numbers of classes and complex hierarchies.

As an example, a programmer can write a generic program in which the virtual function Show is used to show any object in the hierarchy. The user of the program decides at run time, the actual object the function Show will operate on. The programmer has not needed to develop the full range of complex logic needed to handle whatever type of object from the shape class the user will choose at a particular time. Nonetheless, the correct Show function for that object type will automatically be selected during program operation. This concept will be demonstrated in detail in Chapter 8.

4.11 An Example Object Hierarchy

To enable you to relate some of the concepts described previously, we will develop an object hierarchy without using C++ language syntax or its keywords. The class definitions shown below cannot be compiled in an actual C++ program, however, they demonstrate the principles associated with an object hierarchy. We start with the abstract class Vehicle discussed earlier:

Abstract Class Vehicle

Member data:

Speed

Power

Member Functions:

Stop

Go


68 4 THE OBJECT-ORIENTED APPROACH

This class is the most fundamental of all classes of this example. It has encapsulated the bare minimum that is essential for a vehicle. It must possess Power for it to be able to move, and also will have a Speed characteristic to describe its motion. The member function Go will start the vehicle moving, and the other member function Stop will bring it to a stand-still.

New classes with more specific details added to them can then be derived from the Vehicle class. We have done this by forming two new class definitions named

Passenger Transport, and Goods Transport. This class hierarchy is shown in Figure 4-7 where there are two branches coming from its root (base class). The class definitions are shown below:

Derived Class Passenger Transport: derived from Vehicle class

Additional member data:

Number of Passengers

Derived Class Goods Transport: derived from Vehicle class

Additional member data:

Load carrying capacity in Kg.

Note that these two classes inherit all the member data and member functions of the base class Vehicle. For example, if we list everything in the Passenger Transport class we will form the class definition show below:

Derived Class Passenger Transport

Member data:

Speed

Power

Number of Passengers

Member Functions:

Stop

Go

Vehicle

(Base Class)

Goods

Passenger

Transport

Transport

Figure 4-7 Deriving classes from a base class.

4 THE OBJECT-ORIENTED APPROACH 69

Although we did not specifically mention Speed, Power, Stop and Go, they are present in the new derived class as a result of inheritance. Furthermore, the Goods Transport class is a direct descendant of just the abstract class Vehicle and therefore does not inherit anything from the Passenger Transport class.

Therefore, there are two branches, right at the root of this object hierarchy as shown in Figure 4-7.Also, the Passenger Transport class and the Goods Transport class may or may not be abstract classes. Any of these classes can be used to further derive new classes with additional refinements.

In the next class definition, a new class named Passenger Train is derived from the Passenger Transport base class:

Derived Class Passenger Train: derived from Passenger Transport class

Additional member data:

Number of passenger cars

Additional member functions:

Doors Open

Doors Close

Air Conditioning

In this class definition, the members of the Passenger Transport class are in effect added to the already existing members of the Passenger Transport class that have been inherited (and are invisible). If we managed to see the equivalent complete class definition for the Passenger Train class, it would appear as follows - the inherited members are shown in bold italic typeface:

Derived Class Passenger Train

Member data:

Speed

Power

Number of Passengers

Number of passenger cars

Member Functions:

Stop

Go

Doors Open

Doors Close

Air Conditioning

Just as we used Passenger Transport as a base class, the Goods Transport class can be used to derive further classes. An example of a new Goods Train class derived from the Goods Transport class is now given:


70 4 THE OBJECT-ORIENTED APPROACH

Derived Class Goods Train: derived from Goods Transport class

Additional member data:

Number of boxcars

Number of tank cars

Number of open cars

Motorcars are primarily meant for transporting passengers. Therefore, if we wish to form a new class to represent motorcars, the best place to start is the Passenger Transport class. An example class definition for the new Motorcar class is now given:

Derived Class Motorcar: derived from Passenger Transport class

Additional member data:

Engine Capacity

Body Colour

Trim Colour

Number of Cylinders

Wheel Size

Number of Doors

Additional member functions:

Steer

Brake

If we then need a class definition to represent luxury cars, the best starting point is the Motorcar class. The Motorcar class is chosen instead of the Passenger Transport class because Motorcar objects form a more complete sub-object of a Luxury Car class. If we use the Passenger Transport class as the base class of the Luxury Car class, we will have to re-introduce members such as Engine Capacity, Body Colour, Trim Colour, etc. This involves a lot of unnecessary work, is error prone, and does not take advantage of code reuse.

Derived Class Luxury Car: derived from Motor Car class

Additional member data:

Inside Air temperature

Global Position

Additional member functions:

Air Conditioning Control

Power Mirror Control

Power Window control

Cruise Control

Antenna Control

CD Control

4 THE OBJECT-ORIENTED APPROACH 71

In a class hierarchy, future changes that need to be carried out can be done with minimum reprogramming. If the necessary changes are very specific, then the changes are more likely to be made in the most recently derived classes. If the required changes are more general in nature, it is most likely that the changes will be carried out closer to the root of the hierarchy. For example, if all luxury cars are to have automatic navigation in the future, we will add a new member function named Navigate to the Luxury Car class. On the other hand, if all vehicles are to be fitted with automatic navigation facilities in the future, we will add the Navigate member function to the abstract class Vehicle.

Vehicle

(Base Class)

Goods

Passenger

Transport

Transport

Goods

Motor

Passenger

Train

Car

Train

Luxury

Car

Figure 4-8 The example class hierarchy.

A set of object classes that fit into a class hierarchy always has an expansive nature rather than a multiplicity nature. In an expansive situation, additional member data and member functions will be added to the new derived class. In a multiplicity situation more members of the same object type are added to the new class.

For example, an object class representing a house and another object class representing a better house fit nicely into a class hierarchy. On the contrary, the class representing a house and another class representing many houses of the same type as the other class do not fit into a class hierarchy. New, completely different member objects need to exist in the new class.

Although you may have understood how classes are formed, their use may still be unclear. In the coming chapters, we will develop classes and begin to use them. For now, it is important to gain an understanding of what a class hierarchy is and how it is formed.


724 THE OBJECT-ORIENTED APPROACH

4.12Advantages of Object-Oriented Programming

A large part of the programming community has already embraced object-oriented programming as a better way to program. One of the main advantages is the robustness of the programs, a direct result of encapsulation. The changes carried out within an object class have no side effects on other parts of the program, and the internal details of an object class are well insulated from the outside world. This significantly simplifies the maintenance of programs. If in the future, the functionality of a class needs to be enhanced, the additional coding needed will be localised to the class itself and will not affect the functionality of unrelated classes. The changes may not even affect the public interface of the object itself. If we take a real-life example, drivers operate motorcars exactly the same way they did in the past. However, the fuel system has changed from carburisation to fuel injection. While the performance of the object is enhanced, the motorcar is driven exactly the same way through the public interface (the accelerator pedal).

Inheritance permits us to reuse the code over and over again. This reduces reprogramming time and the associated debugging time. It allows us to reduce our time-to-market and lower the cost of software development. The natural relationship between real-life objects and software objects makes it easier to understand the class structures. This is the strategy we used in this chapter to give you a good insight into object classes.

The most powerful and the most useful feature of object-oriented programming is associated with virtual functions and object hierarchies. Using virtual functions enables the program to select the correct function to operate on the objects that are specified at run time. This relieves the programmer from having to write lengthy code to cater for individual objects that may be specified at run time by the user of the program.

4.13Disadvantages of Object-Oriented Programming

In general there is reluctance among programmers who are familiar with procedural programming to embrace object-oriented programming. Object-oriented concepts are quite foreign and require some adjustment in thinking, especially so for novices.

Object-oriented programming is often not usually justified when programs are very small. Also, object-oriented programming may not be the best choice for programs requiring time-critical program execution. However, with the increasing speed of computers this is becoming a less significant issue. Operating systems that burden the computer are typically more of a concern than the object-oriented programs themselves.

4 THE OBJECT-ORIENTED APPROACH 73

4.14 Summary

In this chapter we used real-life examples to promote understanding of objectoriented concepts. We started by differentiating the two programming methods; procedural programming and object-oriented programming. Procedural programming exposes data and functions for inadvertent misuse and it can lead to unexpected side-effects and difficult debugging. Object-oriented programming imposes data hiding and protects data from inadvertent misuse by encapsulating data and functions together to form object classes. The public interface of an encapsulated object class has been explained using real-life examples.

A qualitative explanation was given to explain the abstract object classes and actual object classes. This has then been consolidated using object-oriented terminology to explain abstract classes and real classes. Also, inheritance has been exploited in an example object hierarchy to show how a class hierarchy can be developed.

The use of constructors and destructors has been briefly introduced and will be explained in greater detail in the coming chapters. Instantiation has a close association with constructors, and a given class may have any number of constructors.

The important concepts of polymorphism and virtual functions have been discussed in limited detail due to their relative complexity. They will be further explained and used extensively in Chapter 8. Finally, advantages and disadvantages of objectoriented programming have been discussed.

4.15 Bibliography

Meyer, B., Object Oriented Software Construction, Prentice Hall, 1988.

Firesmith, D.G., Object Oriented Requirements, Analysis and Logical Design, John Wiley, 1993.

Staugaard A. C. (Jr), Structured and Object Oriented Techniques, Prentice Hall, 1997.

Gray, N.A.B, Programming with Classes, John Wiley, 1994.