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

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

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

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

Добавлен: 14.06.2025

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

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

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

56 3 TESTING THE PARALLEL PORT

3.8 Bibliography

Bergsman, P. , Controlling The World With Your PC, HighText Publications, San Diego, 1994.

IBM, Technical Reference – Personal Computer AT, IBM Corporation, 1985. NS LINEAR Databook, National Semiconductor Corporation, 1987.

Savant, C.J., et al., Electronic Design Circuits and Systems, Second Edition, Benjamin-Cummings, Redwood City, 1987.

Kelley, A. and I. Pohl, A Book on C – programming in C, Benjamin Cummins, 1995.

House, R., Beginning with C – An Introduction to Professional Programming, International Thompson Publishing, 1994.

Deitel H.M. and P.J. Deitel C: How to Program, Prentice Hall, 1994.

C programming Language – an applied perspective by L Miller and A Quilici, John Wiley Publishing, 1987.

Hanly, J.R., E.B. Koffman and J.C. Horvath, C Program Design for Engineers, Addison Wesley, 1995.

Rudd, A., Mastering C, John Wiley, 1994.

4

The Object-

Oriented

Approach

Inside this Chapter

ξ

ξ

ξ

ξ

ξ

ξ

ξ

What exactly is object-oriented programming (OOP)?

Encapsulation.

Member data and member functions of an object.

Inheritance and Polymorphism.

Constructors and the Destructor.

Abstract classes.

Class Hierarchies.

4.1 Introduction

In this chapter we will explain object-oriented programming concepts that apply to C++ programming. Object-oriented programming is the newer way of developing software. The superseded style of developing software is known as procedural programming.

In procedural programming, data and functions can be thought of as being ‘out in the open’. In this case data may be used and/or altered by any function, and inadvertent misuse is common, often causing detrimental side-effects to a program’s operation. Also, any changes or modifications to the existing software can cause problems that are very difficult to debug.

In this chapter we use examples from everyday life to gain a qualitative understanding of the concepts that apply to object-oriented programming. We then take a detailed look at the terminology associated with object-oriented programming and define these concepts. By the end of this chapter, we expect you to have developed a good understanding of the object-oriented concepts and terminology you will need when we commence with object-oriented programming in the next chapter.

4.2Conceptual and Physically Realisable Objects

Objects in object-oriented programming resemble the objects we encounter in reallife. An object can be viewed as a self-contained entity, which has some sort of a description and some uses associated with it. The description may list all the features of the object. The uses associated with the object may be a set of functions the object carries out for us, or a set of functions we carry out on the object, or a combination of both types of functions. A software representation of such an object type in object-oriented programming terms is referred to as an object class. The C++ language provides mechanisms to list all the features or properties of an object class and all the functions associated with the object class.

In real-life, we have descriptions of real objects that physically exist and also descriptions of abstract objects that are either imaginary or conceptual. Real objects are tangible whereas conceptual objects are not. While tangible objects can be duplicated, conceptual objects cannot be duplicated for the simple reason that there is no such thing as “two identical concepts”. However, it is possible to have “two identical objects”. The conceptual objects (abstract objects) can be developed into physically realisable objects by including exact definitions of every detail of the object, at which stage a real object may be produced. Then the object definition has passed through the transition from abstract to real.

To better understand this concept, consider a vehicle as an object. The most likely description of a vehicle that comes to mind is an object that is used to transport people or goods, perhaps rolling on wheels, with some form of energy to drive it


4 THE OBJECT-ORIENTED APPROACH 59

along (as shown in Figure 4-1 a). A manufacturer cannot proceed to build a vehicle unless they have determined its specific details. Is the vehicle a train, a bus, a car or something else? If it is a car, is it a small car, a medium car or a large car? What is its engine type and capacity? How many doors should it have? This refinement must continue until every detail of the “vehicle to be built” has been defined. At this stage the object is no longer an abstract object. Once completely defined, any number of “cars” can be manufactured as real objects.

Passengers

Speed

Power

Direction

Control

Go

Stop

ABSTRACT OBJECT – VEHICLE

REAL OBJECT – A CAR

(a)

(b)

Figure 4-1 The concept of abstract objects and real objects.

4.3 Real Objects

Although the cars of this class are identical, when built, they are individual items. Each of these cars will have its own engine, fuel system, braking system, etc. If someone is asked to “Start the engine!”, they cannot start an engine without knowing which car is to be started. Accordingly, the word “engine” does not uniquely identify “an engine”. To be able to do so, the engine must be tagged with a particular car. For example, suppose three cars have been built and they are labelled A, B, and C. Then “Engine of Car A” will uniquely identify an engine. Thus, while “Car” is an object type, “Car A” is an actual object. It is important to understand the difference between the object type and the actual object. The existence of an object type does not necessarily mean that actual objects of that type exist. However, an actual object cannot exist without having its object type in existence.

The terms such as engine, fuel system, braking system, etc. can be used to generally describe those systems. For example, to describe features of the engine of a particular car type, we do not have to say the engine of the ‘blue’ car has such

60 4 THE OBJECT-ORIENTED APPROACH

and such features. We would simply say engines of this particular car type have these features. On the other hand, if an engine of a car is faulty, we must specifically refer to that car by saying ‘the engine of that blue car’ is faulty and needs to be repaired. Therefore, when an object type is described, we can use its terms without having to tag them to a physical object.

4.3.1 Public Interface of an Object

A motorcar was a sophisticated object even in early times. There are certain parts of a motorcar that the user is not expected to access; for example, the fuel injection system. The fuel injection system is not directly accessible to the user; nevertheless, it carries out its functions behind the scenes. On the other hand, the driver of the motorcar has direct access to the steering wheel, the brake pedal, the indicator stalk, etc. These can be referred to as the public interface of the object “Car”. Similarly, in object-oriented programming, every object must have a public interface for it to be useful. An object without a public interface is like a perfectly built car, which is completely encased and sealed off so that no one can ever get into it to drive it.

Private or

Protected Space

Public Space

Figure 4-2 The public interface of an object.

The software objects will also have private functions with some designated purpose that are not directly accessed by the users of the object (like the fuel injection system of a motor car). Therefore, in the most general case, an object is an encapsulated entity with a public interface that has restricted access to its hidden details. How objects can be realised in software will be understood as we proceed through the development of object classes in the coming chapters.

4.3.2 Construction and Destruction of Objects

All cars come to life through some kind of a manufacturing process, which we may refer to as the “construction process”. If needed there can be slight variations to the cars built according to the ‘same’ plan – for example, cars that have different colour. Furthermore, manufacturing processes themselves could be slightly different. In one factory, cars may be built starting from sub-assemblies. In another


4 THE OBJECT-ORIENTED APPROACH 61

factory, cars may be built from scratch. In either case, the same type of car will be produced.

After the car has been brought to physical reality, it can then be driven. At the end of the car’s life it will undergo some sort of destruction process which could take place in a car disposal yard. Destruction is an important process, which carries out the disposal of unwanted items to maintain environmental cleanliness and to allow the efficient management of resources. In the case of computer programs, object destruction is necessary for the efficient management of memory.

The techniques available in object-oriented software development provide mechanisms to realise all these aspects. Although we can draw analologies between the objects in our day-to-day life and the software objects, the real power of objectoriented programming in C++ comes from the combination of object-oriented programming techniques and C++ programming techniques.

4.4 Object Classes

An object class describes a particular type of object. The object class does not refer to a real object but the type of those real objects yet to be created. If we take an analogy from everyday life; a building plan is analogous to an object class – not the building itself. The same building plan can be used to create any number of buildings. Likewise, the same object class can be used to create any number of objects. Each object that will be created according to an object class will reside in the memory of your computer. If more objects of the same type are created, more memory will be used.

Member Data

Member Functions

Constructors &

Destructors

Figure 4-3 Components of an object class.


62 4 THE OBJECT-ORIENTED APPROACH

Each object class will have its own name, also known as the object type name. The word class is a keyword in C++. It is used to identify a detailed plan with a name. Programmers are free to choose class names when developing new classes.

Each object class must have a class definition. Similar to the case for real-life objects, the properties or features of the object and the functions associated with the object are listed in its class definition. The properties or features are given the name member data of the class and the functions associated with the object are referred to as member functions.

Among the member functions are two special types of functions. The first type can have more than one function per class and are known as constructors. Constructors are used by the program to create each individual object (that resides in memory). The second type has only one function per class and is known as a destructor. Destructors are used by the program to free the memory that a variable used once the variable is no longer needed. If a constructor is not provided, the C++ compiler will provide a default constructor (invisible to the programmer). Similarly, if a destructor is not provided, the C++ compiler will add a default destructor (also invisible to the programmer).

Private:

Member Data

Member Functions

Protected:

Member Data

Member Functions

Public:

Interface to Outside

Member Data Program Code

Member Functions

Figure 4-4 Public interface of an object class .

Some of the class members (both data and functions) can be publicly accessed; other members will have restricted access. The publicly accessible members provide the public interface of the object as shown in Figure 4-4. These include the public member data and public member functions. Members with more restricted access are known to have either private or protected access attributes.

4 THE OBJECT-ORIENTED APPROACH 63

4.5 Encapsulation

Grouping the member data and member functions together is known as encapsulation. There are some great benefits associated with encapsulation. First of all, encapsulation limits access to the internal details of the object. Access to the data is always through controlled and supervised means. In general, access will be restricted to most data members where data should not be freely accessible or changeable. Some of the functions may also have restricted access.

Access to the object is allowed only through the public interface. This ‘restricted visibility’ to member data and member functions is also known as information hiding. Sometimes it is not necessary to know the internal details of an object. In this case it is often sufficient to just be able to know how to use it. A good example is a scroll bar. It is sufficient for the programmer to know how to place a scroll bar in an application to make the screen scroll. The scroll bar’s internal workings are hidden and normally are of no concernt to the programmer.

While all these restrictions are imposed to functions outside of the class, internally, any function of the class can manipulate or access any other member of the same class. This provides efficient operation of object-oriented programs for the following reasons. It eliminates the need to declare member data within the functions and also the need to pass member data as parameters to member functions. While an ordinary non-member function can only return one value, the member functions can return ‘more than one value’ by being able to change any number of the data members of the class.

4.5.1 Object Instantiation

The process of creating an actual object is known as object instantiation. Therefore, to instantiate an object of a particular class, one of the constructors of that class must be called. The constructor resembles “the manufacturing process” in our ‘car’ analogy. The constructor, like any other function is a function written in C++. It must be called to create a physical object of the object class. While the object class is of type ‘Car’, the actual objects created, which we refer to as class objects, could be named A, B, C, etc. They are all equivalent, perhaps with minor differences like their colour. In object-oriented programming, a class definition does not occupy memory. However, a class object does occupy memory. Likewise a building plan does not occupy any land, whereas the actual building occupies finite space.

In object-oriented programming, the constructor must be called to create an actual object. At the time of calling the constructor, you can pass parameters to it in a likeness to selecting the colour of a car to be built. In a class definition, there may be more than one constructor. In our car analogy, a car may be constructed from scratch or may be constructed from subassemblies.


64 4 THE OBJECT-ORIENTED APPROACH

4.6 Abstract Classes

Abstract classes can be viewed as initial conceptual class definitions which are insufficiently complete to carry out instantiation. Many good hierarchies of class objects will often start with an abstract class. The real power of abstract classes cannot be properly demonstrated until some advanced concepts of the C++ language are explained in the coming chapters.

An abstract class needs to be developed to become a real class that has working functions if it is to be able to instantiate real objects and use them. There is no such thing as ‘an abstract object’ for the simple reason that anything abstract does not physically exist. In our ‘vehicle’ example, there will definitely be a characteristic such as speed. However, we cannot discuss how to increase or decrease speed until we know more details of the actual vehicle. We can also include ‘functions’ to increase and decrease the value of the speed. However, we cannot define the exact steps these ‘functions’ should take to increase or decrease the speed without knowing whether the vehicle is a car, or a train, or something else. In an analogous class definition, these types of functions are known as pure virtual functions. They are pure because their actions (bodies) cannot be defined yet, and virtual because their actions (bodies) need to be defined in future derived classes to carry out their required tasks.

4.7 Class Hierarchies

A class hierarchy is a set of classes that are developed starting from one or more classes known as base classes (located at the root of the hierarchy). The new classes developed from the base classes are known as derived classes. The derived classes are more detailed and complete than their base classes. One of the most important benefits of object-oriented programming is code reuse. Developing class object hierarchies greatly facilitates the ability to reuse code by not having to rewrite code that new code is based on. Object-oriented programming allows us to re-use already written code as often as we like.

The base class can be an abstract class, although this is not an essential requirement. As mentioned earlier, no real object can be instantiated from an abstract class. However, it is useful to form a general abstract base class by including the essential member data and member functions that will be common to all objects of the derived classes of the hierarchy.

As an example, if you consider a graphics program which works with geometric shapes such as lines, circles, triangles, squares, etc; a base class definition can be formed to move, scale, hide, show, stretch any of these objects. Let us call this class the Shape class. The class that we form, without referring to a specific object, can be an abstract class. As mentioned above, base classes do not need to be abstract classes. The abstract class will define the functionality of all objects of the hierarchy without specifying a particular object type.

4 THE OBJECT-ORIENTED APPROACH 65

The derived classes must be more specific than the abstract class. For example, there can be a derived class, which specifically works with a circle. Let us name this the Circles class. Then, all functions within the Circles class such as Move, Scale, Hide, Show, and Stretch can be coded specifically to operate on circle objects. As you can imagine, it is very difficult to transfer the functionality of the Circles class over to a new class named Squares to work with squares! You will need to make so many changes to be able to operate with squares in place of circles. It is easier to directly derive the Squares class from the abstract class Shape, and then define the functions the Squares class needs. Although the abstract classes cannot be used to instantiate new objects, they have a very powerful use associated with virtual functions and late binding. We will discuss these two concepts in Chapter 8.

4.8 Inheritance

Inheritance is closely associated with class hierarchies. When a new object class is derived from a base class, the new class is said to inherit all the member data and member functions of the base class. This is the mechanism that underlies code reuse. The functions and data of the base class automatically exist in the derived class. They do not need to be written again. To provide the new class with functionality beyond that of the base class, we only need to add whatever additional data and functions are necessary. It is also possible to modify the inherited functions to suit their more specific tasks. However, there may need to be restrictions for access to some inherited data and functions.

Shape

Show

Hide

(Abstract Base Class)

etc

Circles

Squares

Triangles

Show

Show

Show

Hide

Hide

Hide

etc

etc

etc

Figure 4-5 Inheriting from an abstract class.

As an example, consider the graphics program we mentioned earlier. We discussed an abstract class named Shape. In that class we had graphics functions such as Move, Scale, Show, Hide, Stretch, etc. If we need a new class to specifically work with circles, then we can use the abstract class Shape as the base class and