Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 An Introduction to C++ Computer Language Using UML --BASICS-- Embedded Controller Designers For Copyright©1998 by Sayeed Nurul Ghani. All rights reserved.

Similar presentations


Presentation on theme: "1 An Introduction to C++ Computer Language Using UML --BASICS-- Embedded Controller Designers For Copyright©1998 by Sayeed Nurul Ghani. All rights reserved."— Presentation transcript:

1 1 An Introduction to C++ Computer Language Using UML --BASICS-- Embedded Controller Designers For Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

2 2 Introduction Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

3 3 Relevance Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

4 4 Difference Between Desktop Computer OS and Real-time OS Desktop computer OS takes control of the computer as soon as the machine is switched on. The application starts next. Application is compiled and linked separately from the OS. In real-time embedded systems the application and the RTOS are linked. At bootup the application takes control first and then the RTOS is started from within the application. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az- 85737

5 5 Desktop Computer OS & RTOS (cont) Desktop computer OS has significant protection from application, viz checking validity of any pointer passed from the application to the OS function. RTOS often do no check this in favor of performance gains. The underlying thought is that if the application is about to crash it does not matter if it takes the RTOs with it. The whole system will have to be rebooted in any case. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

6 6 Desktop Computer OS & RTOS (cont) To save memory RTOS includes just those system services required by the embedded system -- no less no more. They allow extensive configuration before linking with the application. Common OS functions such as file managers, I/O drivers, utilities, memory management may be left out if not needed. Such facilities are usually absent in desktop OS. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

7 7 Objectives On completion of the course the participants should be able to:  Appreciate the principles of object- oriented programming.  Produce C++ code for off-line calculations, and on-line computer control in real-time or in accelerated time. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

8 8 Objectives  Design and implement moderately complex systems in C++.  Develop a feel for industry standard Unified Modeling Language (UML) without making any conscious effort.  Have a working knowledge of industry standard Microsoft Visual C++ compiler, and its Integrated Development Environment (IDE). Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

9 9 Course Structure Module 1 Module 2 Module n Lab Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

10 10 Overview of Programming Techniques Unstructured Programming Main Program DATA Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

11 11 Overview of Programming Techniques Procedural Programming Main Program DATA Procedure 1Procedure 2Procedure 3 main programprocedure Executions of procedure Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

12 12 Overview of Programming Techniques Modular Programming Main Program GLOBALDATA Procedure 1 Module 1 global data + local data Module 2 global data + local data Procedure 3 Procedure 2 Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

13 13 Overview of Programming Techniques Object Oriented Programming Object 1 data, operations Object 2 data, operations Object 4 data,operations Object 3 data, operations Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

14 14 Text Books Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

15 15 What is Object-orientation ? Object-oriented programming system (OOPS) stands on three pillars: (b) type derivation - inheritance (c) polymorphism - dynamic binding (a) abstract data typing - classes, Definitions will be provided latter. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

16 16 Chapter 1 Overview of a C++ Class Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

17 17 #include // Prog 1.1 void main() { const int i = 5; int k; for ( k=0; k < i; ++k) { cout << "Numbers are: " << k << " " <<endl; } Simple Input and Output Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

18 18 Simple Input and Output (cont) Manipulator Purpose dec convert to decimal hex convert to hexadecimal endl add end of line and flush setw ( int w ) set output field width #include if setw(int w) is used. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

19 19 Simple Input and Output (cont) Effect of some manipulators lasts after the statement in which it is used. cout << hex << k << dec << f; For input of a value for gamma use cin >> gamma. Operator << is called insertion operator. Operator >> is called extraction operator. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

20 20 Simple Input and Output (cont) #include // Prog1.2 enum color { RED, BLUE, GREEN, VIOLET }; const double PI = 3.142; void main() { cout << "Message\"Valve VN22 OPEN\"." << endl; cout << "DATE:HOURS:MINUTES:SECONDS:May 20,1998:15:55:20" << endl; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

21 21 Simple Input and Output (cont) Exercise Prog1.1 & 1.2 Compile and run Prog1.1. If it does not compile debug the program so that it runs. Compile and run Prog1.2. Carefully study the output. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

22 22 Why C++ class ? The class concept which is central to all object-oriented languages imparts tremendous power and flexibility to such programming paradigm. From structure to class is a seamless transition. Maintenance of software written in any language other than object oriented becomes extremely difficult and costly Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

23 23 because a small change in any part of the program ripples through the entire code requiring extensive debugging. In object oriented language any alteration made to a class effects that class only and do not effect any other part of the program. This makes software maintenance a doddle. Why C++ class ? (cont)

24 Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-8573724 Maintenance of software written in any language other than object oriented becomes extremely difficult and costly because a small change in any part of the program ripples through the entire code requiring extensive debugging. Why C++ class ? (cont)

25 25 What is a C Structure? (cont) #include void main(void); /* Structure definition */ struct employee_record { char surname[30]; char first_name[30]; char middle; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

26 26 What is a C Structure ? (cont) char ssn[12]; int hours; }; void main(void) { /* Declaring a structure variable - ghani */ struct employee_record ghani; /* Initialize the structure ie assign values to the members of structure ghani */ strcpy(ghani.surname, “GHANI”); Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

27 27 What is a C Structure ? (cont) strcpy(ghani.first_name, “Sayeed); ghani.middle = ‘N’; strcpy(ghani.ssn, “805-95-6065”); ghani.hours = 40; /* Print the member variables of structure ghani */ Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

28 28 What is a C Structure (cont) printf(“Surname: %s\n”,ghani.surname; printf(“First name: %s\n”,ghani.first_name; printf(“Middle initial %c\n”,ghani.middle; printf(“SSN#: %s\n”, ghani.ssn; printf(“Hour worked: %d\n”,ghani.hours; } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

29 29 What is a C++ Structure ? (cont) In C++ functions or operations can also be included. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

30 30 C++ Structure (cont) #include // Prog1.3 #include struct employee_record { //Structure definition char surname[30]; char first_name[30]; char middle; char ssn[12]; int hours; employee_record(); Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

31 31 C++ Structure (cont) employee_record Ghani; The above statement constructs an instance of the structure employee_record and initializes it. ‘employee_record::employee_record()’ is called CONSTRUCTOR function. Ghani.print_it(); The above statement prints the contents of the structure. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

32 32 What is a Global Variable ? If the structure was declared as struct employee_record { ….. } Ghani; then Ghani would have been a global variable. Because global instances or global objects are rather large, and thus takes up large amount of memory its is prudent to ensure that they are automatically destroyed as Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

33 33 Why Avoid Global Objects ? early as feasible. Locally defined class instances disappear as soon as the program execution exits the local definition. In Prog1.1 and Prog1.2 the instances are defined as local objects within the scope of the main(). Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

34 34 Why Use Local Objects ? Other reasons for using locally instantiated objects are related to gain in performance, and ease with which the instance can be destroyed, whenever required, by calling DESTRUCTOR function. DESTRUCTOR function must be called implicitly using suitably defined block scope. This is discussed in greater details latter. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

35 35 What is Accessibility of C++ Structure ? The biggest disadvantage of using a structure to encapsulate data and functions is that both the data members and the functions are publicly accessible. There is no way of restricting the instantiating code from accessing them. In other words code outside the structure definition will always be able to access the data and functions members once an object Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

36 36 C++ Structure Accessibility (cont) has been instantiated. ………. employee_record Ghani; Ghani.print_it(); will print the surname Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

37 37 C++ Structure Accessibility (cont) surname[30]; first_name; middle; ssn[12]; hours; employee_record(); show_it(); Structure Public Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

38 38 What is C++ Class Accessibility ? The C++ keyword class allows use of keywords private, protected and public for controlling access of class data members and functions. Class data members are called attributes. Class functions are called operations. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

39 39 Accessibility in a C++ class (cont) Class Private Public employee_record() show_it() surname[30] first_name[30] middle ssn[12] Operations Attributes Protected will be discussed later when inheritance is introduced. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

40 40 UML Diagram for a Class Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

41 41 Accessibility in a C++ class (cont) #include // Prog1.4 class PulseWidthModulation { public: int pwm_device_configuration; //Member attribute - base class data object public: PulseWidthModulation() { pwm_device_configuration = 20; } //Constructor }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

42 42 Accessibility in a C++ class (cont) Attributes and operations in a class are, in general, not available to an user of the class. The only way an user can access them is by instantiating the class, ie by creating an object using the class. However, both attributes and functions must be declared public to be accessible. The attributes and operations are, however, available to an user, without instantiating, if they are preceded with the keyword static. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

43 43 Accessibility in a C++ class (cont) Both attributes and functions in a C++ class when declared private can only be accessed by other member functions of the class and friend functions. They are not accessible to the user through creation of an object of type class. Keyword protected will be discussed latter when the concept of inheritance is introduced. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

44 44 Accessibility in a C++ class (cont) Exercise Prog 1.4 Introduce a function in Prog1.4 to print attribute pwm_device_configuration. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

45 45 Accessibility in a C++ class (cont) #include // Prog1.5 class PulseWidthModulation { private: int pwm_device_configuration; //Member //attribute - base data object public: PulseWidthModulation() { pwm_device_configuration = 37; } //Constructor function int fetch() { return pwm_device_configuration; }}; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

46 46 What is Visibility in a C++ class ? Visibility is accessibility without access control exercised through the use of keyword private. A class attribute or operation which is visible can be made inaccessible by using the keyword private. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

47 47 UML Class Diagram Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

48 48 Sequence Diagram Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

49 49 Collaboration Diagram Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

50 50 Visibility in a C++ class (cont) #include // Prog1.6 int x_coordinate = 1000; //Global base data object class GuidanceSubsystem { public: int x_coordinate; //Member attribute - base data //object public: GuidanceSubsystem() { x_coordinate = 10; } //Constructor function }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

51 51 Visibility in a C++ class (cont) In the above Prog1.6 classes GuidanceSubsystem and FlightCrewInterfaceSubsystem are two separate classes completely unrelated. When the operation print_it() in class FlightCrewInterfaceSubsystem is invoked it does not find the integer variable x_coordinate in class FlightCrewInterfaceSubsystem. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

52 52 Visibility in a C++ class (cont) There is an attribute integer x_coordinate in class GuidanceSubsystem, but it is invisible to print_it() because no communication channel has been established between the classes. Classes GuidanceSubsystem and FlightCrewInterfaceSubsystem have their own completely different scopes or name spaces. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

53 53 Visibility in a C++ class (cont) Attempt is then made to search for the identifier x_coordinate in immediate surrounding, thus reaching the global integer variable x_coordinate. The operation (function) print_it() in class FlightCrewInterfaceSubsystem is declared public. It is accessible to the user main() through object fcis resulting in this global x_coordinate to be printed. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

54 54 Visibility in a C++ class (cont) Attempt may be made to force operation print_it() in class FightCrewInterfaceSubsystem to access attribute x_coordinate in class GuidanceSubsystem by using scope resolution parameter :: as follows. void print_it() { cout << "x_coordinate = " << GuidanceSubsystem :: x_coordinate << endl; } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

55 55 Visibility in a C++ class (cont) This will result in error message because of visibility restriction imposed by the class scope. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

56 56 What is a Constructor Function in a C++ Class ? Constructor functions are used to construct a class object in the memory, and then initialize it. Thus, object creation results in using up memory. In Prog1.6 GuidanceSubsystem() { x_coordinate = 10; } is the constructor operation. An object gs of type class GuidanceSubsystem is created in the main() by the statement GuidanceSubsystem gs; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

57 57 What is the Structure of a C++ Program ? Member functions should be compiled separately. C++ programs are usually complex and large. Separate compilation is usually used to build the final executable. -- First put the class definition in a separate file called the header file class_name.hpp. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

58 58 Structure of a C++ Program (cont) -- Next put all the class operation definition in another file. Call it class_name.cpp. At the beginning of this file include the class_name.h file mentioned above. -- Finally, put the main program in a third file. Call it executable_name.cpp. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

59 59 Structure of a C++ Program (cont) Content of the Apu.h // Prog 1.7 class Apu { private: //Member attribute - base data object int essen_time; int wow_timedelay; public: Apu(); //Constructor function Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

60 60 Structure of a C++ Program (cont) void reset(); //Declaration of operation void display(); //Declaration of operation }; Content of the Apu.cpp file #include #include "Apu.h" Apu::Apu() { //Constructor function essen_time = 0; wow_timedelay = 0; } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

61 61 Structure of a C++ Program (cont) Exercise Prog1.7 Sketch class diagram for Prog1.7. Draw sequence and collaboration diagrams to print out the values of essen_time and wow_timedelay. Map the above UML diagrams to a ‘void main()’ function. Compile and run the program. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

62 62 Structure of a C++ Program (cont) Content of the main.cpp file #include "Apu.h" void main () { Apu apu; //Instantiate object apu of type class Apu apu.display(); apu.reset(); apu.display(); } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

63 63 Structure of a C++ Program (cont) iostream.hclass_a.h math.h prog_b.cppclass_a.cpp prog_b.o class_a.olibrary prog_b.exe main.cpp main.o Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

64 64 Structure of a C++ Program (cont) Inline definition for member functions -- Create one file class_name.cpp -- This file contains both the class definition, and inline function definitions. -- The main function can be included in this one file or in a separate file executable_name.cpp. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

65 65 Structure of a C++ Program (cont) -- Another approach to inline definition is to declare the functions in the class definition (in the class_name.cpp file), and then to include the function definitions with the keyword inline first, then the function return type, and finally the class name with the scope resolution operator :: followed by the function name. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

66 66 Structure of a C++ Program (cont) Content of the Apu.cpp file //Prog 1.8 #include class Apu { private: //Member attribute - base data object int essen_time; int wow_timedelay; public: Apu(); //Constructor function Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az- 85737

67 67 Structure of a C++ Program (cont) Note only very short functions are suitable for inline definition. Exercise Prog1.8 Complete the above program to print out the values of essen_time and wow_timedelay. Compile and run the program. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

68 68 Structure of a C++ Program (cont) Content of the file main.cpp #include "Apu.cpp" void main () { //Instantiate object apu of type class Apu Apu apu; apu.display(); apu.reset(); apu.display(); } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

69 69 Structure of a C++ Program (cont) IMPORTANT A class member operations cannot be redeclared or redefined. Definition of a class member function cannot be included without it being declared ie function prototype introduced inside the class definition. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

70 70 How Default Arguments are Supplied to Member Functions ? Default arguments for member functions are supplied in the function declaration ie in the function prototype. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

71 71 Default Arguments (cont) RULES All arguments need not be supplied with default arguments. Once default value is supplied to one argument, all following arguments to the end of the list must be supplied with default arguments. -- funct(int, double); //Correct - no defaults -- funct(int, double = 2.5, int = 1); //Correct Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

72 72 Default Arguments (cont) //Incorrect, default value must be // provided to the end of the list -- funct(int,int = 1, double = 2.5, int) ; // Corrected member function prototype -- funct(int, int =1, double = 2.5, int = 2); Member function calls not containing values for trailing arguments are supplied with the default values from the function prototype. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

73 73 Default Arguments (cont) If in an earlier declaration of a function prototype an argument was given a default value, this argument need not be given the same default value in a subsequent redeclaration of the prototype. -- funct(int, int = 2); // Earlier declaration -- funct(int = 4, int); // 2nd argument need not // be given the same default value 2 again. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

74 74 Default Arguments (cont) Arguments of a function prototype which have been given default values in an earlier declaration cannot be again given even the same default values in a subsequent redeclaration. -- funct(int =1, double = 2.5); //Earlier //declaration -- funct(int =2, double =3.5); // Subsequent // redeclaration Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

75 75 Default Arguments (cont) #include // Prog1.9 class LubricationSystem { private: double oil_temp; //Attribute base class data type -- private by default double oil_temp_rise; public: //Default argument is supplied in the declaration of //the member function prototype void set_oil_temp(double x_deg_C = 125); Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

76 76 Default Arguments (cont) Exercise Prog1.9 Sketch the UML diagrams for Prog1.9. Compile and run the program, and explain its behavior. Experiment with various features of default arguments discussed above. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

77 77 How to Specify Default Constructor ? A default constructor is that with no arguments or with all default arguments, so that it can be called without any arguments to pass. In the absence of any default constructor function, the compiler will generate a default constructor. This computer generated default constructor initializes Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

78 78 Default Constructor (cont) all member data objects ie attributes to zero. It is usual for default constructor function not to have any arguments. It is common to initialize all attributes to zero. This is the classical and most common form of default constructor. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

79 79 Default Constructor (cont) class A { ……….. A(); //Declaration of default constructor ……….. }; A::A() { a = 0; b = 0; c = 0; } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

80 80 Default Constructor (cont) class A { ……….. A(); //Declaration of default constructor ……….. }; A::A(int xa = 10, double xb = 2.5) { a = xa; b = xb; } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

81 81 Default Constructor (cont) Default constructor can contain default arguments. This is shown in the code above. If all arguments are provided with default values, then the constructor can be called with no arguments. It is illegal for default or any overloaded constructor operation to have any return value. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

82 82 Default Constructor (cont) It is common to provide several overloaded constructor functions. Each version must have explicitly different types of arguments. Copy constructor allows an object of the class to be declared, and then initialized with the contents of another class object. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

83 83 How Constructors are Used to Initialize a Class Object ? A default constructor will create a class object in RAM, and then initialize the class data members (attributes) with the default values. However, a general purpose constructor after creating a class object in RAM, should be able to initialize it with any values supplied through the argument list. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

84 84 Constructors Initialize Class Object (cont) class A { int i, j; double b, c; B* b_ptr; public: A( int xi, int xj, double xb, double xc, B* xb_ptr) { Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

85 85 Constructors Initialize Class Object (cont) i = xi; j = xj; b = xb; c = xc; b_ptr = xb_ptr; ……… }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

86 86 Constructors Initialize Class Object (cont) void main() { …… A a_obj(1, 2, 3.7, 8.2, &b_obj); ……. } The above constructor call will create an object a_obj of type class A, and then initialize it with the arguments in the call. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

87 87 What is a Destructor Function ? Destructor functions are provided to destroy class objects whenever a human programmer wishes to do so in order to recover memory. Class A { char* top ……. A(); //Constructor function ~A(); //Destructor function Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

88 88 Destructor Function (cont) ……. }; A::A() { top = new char[2048]; } A::~A() { delete top; } A::A() { top = new char[2048]; } In the above statement the operator new reserves 2048 bytes of memory, and returns the start address to the pointer top. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

89 89 Destructor Function (cont) A::~A() { delete top; } In the above statement the operator delete releases the chunk of memory pointed to by pointer top. Destructor operation has the same name as the class, but preceeded by ~ to mean reverse of constructor. Symbol for complement operator ~. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

90 90 Destructor Function (cont) Destructor function must be devoid of any arguments. There can be one and only one destructor function for a class. This is because it is illegal for a destructor function to have a return value, and accept arguments. Hence, overloading of destructor operation is not possible. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

91 91 Destructor Function (cont) In the absence of destructor function the compiler will automatically generate one. This is adequate for a simple class object which does not acquire memory outside the object boundary. Explicit destructor function is essential for releasing memory acquired outside the object boundary by use of such operator as new shown earlier. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

92 92 What is a Friend Function ? Functions which are not class members are barred from accessing private features (objects and operations) of the class. If, however, a keyword friend precedes these nonmember function prototypes in the class definition, then the private features becomes accessible to the nonmember functions. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

93 93 Friend Function (cont) Friend functions are truly nonmember functions. Therefore, scope resolution operator :: need not be used in the definition of these functions for attaching appropriate class names. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

94 94 Friend Function (cont) #include // Prog1.10 class Starter { int starter_volts_low; //Attribute base class data type -- private by default public: Starter() { starter_volts_low = 0; } //Default //constructor void set_starter_volts(); friend void display(Starter); //Friend function //declared }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

95 95 Friend Function (cont) Because a friend function is not a class member it is not called through a class object using a class member access syntax (object.operation), ie in above Prog1.10. display(starter) and not starter.display(starter) is the correct statement to use. However, a friend function still has to use class member access syntax for either private or public class features. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

96 96 Friend Function (cont) eg in Prog1.10 above cout << obj.starter_volts_low << endl; Friend functions are used to minimize a class object size, and to enhance its performance. A function can be a friend to more than one class. Thus, defining a global function accessible to more than one class becomes unnecessary. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

97 97 Friend Function (cont) An overloaded operator functions for classes can be easily and flexibly implemented using a friend function. Declaring a routine or an operation, written in a language other then C++, as a friend will allow a class data feature (attribute or function), to be accessed by the routine irrespective of type of access protection provided in the class definition. Assembler language is often used for enhanced speed. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

98 98 Friend Function (cont) A friend function defined inline is in the scope of the enclosing class. That defined out-of-line is outside the scope of the enclosing class. A friend function cannot be inherited. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

99 99 Friend Function (cont) #include // Prog1.11 class Starter { enum { FALSE, TRUE }; bool starter_volts_low; //Attribute base class data type -- private by default public: //Default constructor Starter() { starter_volts_low = FALSE; } void get_starter_volts(); //Friend function declared and defined in class definition Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

100 100 Friend Function (cont) Exercise Prog1.11 Compile and run Prog1.11. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

101 101 What is the Syntax for Global Class Definition ? class class-name { access_specifier: attributes; access_specifier: return_type in-line_operation(); return_type out-of-line_operation_prototype(); Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

102 102 Syntax for Global Class Definition (cont) return_type in-line_operation_prototype(); friend return_type in-line_operation() { }; friend return_type out-of-line_operation_prototype(); }; return_type class_name :: out-of-line_member_operation_definition Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

103 103 Syntax for Global Class Definition (cont) inline return_type class_name::inline_operation_definition() { } return_type out-of- line_friend_operation_definition() { } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

104 104 What is A Constant Object ? A class object can be declared to be constant in a manner analogous to fundamental data types. const A a_obj; A constant object must be initialized. Assignment to a constant object is illegal. Modification of the state (class data members) of a constant object is not allowed. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

105 105 Constant Object (cont) Member functions generally modify class data members. Therefore, with a constant class object such functions must not be used. Keyword const is suffixed with a member function to tell the compiler that the function will not modify the object. Such functions can be safely used with a constant object. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

106 106 Constant Object (cont) class A { public: A(int i = 1, double f = 2.5, int j = 2); //Constant function prototype double func_1() const; ……… }; double A::func_1() { return f; } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

107 107 A Constant Object (cont) Member functions declared constant can be used with non-constant objects; but non- constant member functions cannot be used with constant objects. If in a function an argument is declared a reference to a constant object, then it must be for input only. Because this object is declared constant, only constant member functions of this object type (class) can be invoked. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

108 108 Constant Object (cont) The above restriction does not apply to input only class objects passed by name. The copy of this object is non-constant. Any member functions of this object type can, therefore, be invoked. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

109 109 Maximize the Use of -- const Check whether the functions: Have any constant behaviour -- return a constant value. Accepts constant arguments. Operate without any side effect -- constant object. const type f(…); //Constant object returned. type f(T* const arg); //Function argument is // a constant pointer. The pointer Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

110 110 Maximize the Use of -- const (cont) //cannot be changed, but change of //pointed-to object is allowed. type f(const T* arg); //Pointer to a constant //object. It is legal to change the pointer //arg, but not so for the object pointed to. type f(const T& arg); //Reference to a //constant object. It is illegal to change //the object arg. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

111 111 Maximize the Use of -- const (cont) type f(const T* const arg); //A constant //pointer to a constant object. Neither the //pointer, nor the object can be changed. type f(…) const; //The state of the object does //not change (no side-effect). //Therefore, this type of //operations can be applied to //constant objects. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

112 112 What is a Mutable Class Data Object ? In general, a constant function is not allowed to alter the values of its class data members. For certain reasons, it may be necessary for a constant function to change one of its class data members. The keyword for such a data member is mutable. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

113 113 Mutable Class Data Object (cont) class A { mutable int k; double f; public: double func_1() const { //Allowed because k is declared mutable k++; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

114 114 Mutable Class Data Object (cont) return f; } int func_2() const { return k; } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

115 115 What are Pointers ? A pointer to a double is declared as: double* ptr; ptr ? Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

116 116 Pointers (cont) int* int_ptr_1, int_ptr2; int_ptr_1 int_ptr2 ? ? Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

117 117 Pointers (cont) int *int_ptr_1, *int_ptr_2; int_ptr_1 int_ptr_2 ? ? Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

118 118 Pointers (cont) Dereferencing a pointer allows access to the object. *float_ptr = 3.5 * *int_ptr; ? float_ptr = 3.5 * int_ptr ? Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

119 119 Pointers (cont) A pointer is declared with the * operator. It associates the pointer with the object name, and not the type name. int* int_ptr_1, int_ptr2; // BEWARE //int_ptr_1 is a pointer to an integer //object, but int_ptr_2 is not a //pointer. int_ptr_2 is an integer //variable. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

120 120 Pointers (cont) int *int_ptr_1, *int_ptr2; //NOW both //int_ptr_1 and int_ptr_2 are valid //pointers to an integer object(s). OR declare pointers as: int* int_ptr_1; int* int_ptr_2; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

121 121 Pointers (cont) A pointer can only be used after it has been assigned a value. int k; //An integer variable. float f; //A floating point variable. int* int_ptr; //A pointer to an integer. int_ptr = &k; // A pointer has a value. int_ptr = k; //Error, k is not a pointer. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

122 122 Pointers (cont) int_ptr = &f //Error, type mismatch. float* float_ptr = &f; //A pointer initialized. int* int_ptr = &k; //A pointer initialized. Dereferencing a pointer allows access to the object. *float_ptr = 3.5 * *int_ptr; Pre-increment object pointed to: ++(*ptr) or ++*p Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

123 123 Pointers (cont) Pre-increment object pointed to: ++(*ptr) or ++*p Post-increment object pointed to: (*ptr)++ but not *ptr++ Access via pointer that has been pre- incremented: *(++ptr) or *++ptr Access via pointer and the post-increment pointer: *(p++) or *p++ Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

124 124 Pointers (cont) The value of a pointer is allowed to change on the fly. Hence, the same dereferenced name can point to more than one object at different times. Very useful for polymorphism. int k, kk; int* ptr = &k; *ptr = 5 //k is 5 int* ptr = &kk; *ptr = 10; // kk is 10 Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

125 125 Pointers (cont) It is illegal to dereference a null pointer. int* ptr; ptr = 0; //Null pointer *ptr = 100; //Illegal, resulting runtime error ptr = &k; //A valid address assigned to ptr *ptr = 100 //Okay, k is now 100 ptr = 320; //Error, non-zero integer; must //be valid address Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

126 126 Pointers (cont) Constant pointer or pointer to a constant object or a constant pointer to a constant object. -- A constant pointer once initialized cannot be modified. -- A pointer to a constant object can hold the address of either a constant or a non-constant object. However, the pointer cannot be used to modify the object. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

127 127 Pointers (cont) -- A pointer to a non-constant object cannot hold the address of a constant object. Pointer to: an object of type T: T* p; a constant object of type T: const T* p; Constant pointer to an object of type T: T* const p; or T const *p; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

128 128 Pointers (cont) Constant pointer to a constant object of type T: const T* const p; int k, kk; int* const const_int_ptr = &k; //Constant //pointer must be initialized. const_int_ptr = &kk; //Error, constant //pointer cannot be modified const int* ptr_cons_obj; //Pointer to a //constant object Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

129 129 Pointers (cont) ptr_cons_obj = &k; //Okay to hold the address //of a non-constant object //in a pointer to a constant //object. *ptr_cons_obj = 25; //Error, okay to hold //the address of a non-constant //object in a pointer to a constant //object, but cannot modify the //non-constant object. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

130 130 Pointers (cont) const int CONST_INT = 10; int* int_ptr; int_ptr = &CONST_INT; //Error, illegal to //store the address of a constant object in a //pointer to a non-constant object. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

131 131 Pointers v Arrays int record[11]; //Array converted to pointer int* ptr_record = record; 0 1 2 3 4 5 6 7 8 9 10 ptr_record Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

132 132 // Access via pointer: *ptr_record = 70; //Access as array: ptr_record[2] = 5; Pointers v Arrays 0 1 2 3 4 5 6 7 8 9 10 ptr_record 70 0 1 2 3 4 5 6 7 8 9 10 5 Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

133 133 Relationship Between Pointers and Arrays (cont) const int const_array[] = { 5, 4, 3, 2, 1 }; int* ptr_const_array = const_array; //Illegal, //pointer not declared pointing to a //constant object. const int* ptr_const_array = const_array; //Ok *++ptr_const_array = 56;//Error, cons_array //defined constant. ptr_const_array now //points to element const_array[1]. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

134 134 How Do Objects Communicate ? Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

135 135 Class Diagram Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

136 136 Sequence Diagram Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

137 137 Collaboration Diagram Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

138 138 How Does Two Objects Communicate ? #include // Prog1.12 enum { FALSE, TRUE }; class Shutdown { bool loss_both_egt_sd; //Attribute base class data //type -- private by default public: //Default constructor Shutdown() { loss_both_egt_sd = FALSE; } bool get_loss_both_egt() { return loss_both_egt_sd; } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

139 139 Object Communication (cont) Exercise Prog1.12 Write a main program for Prog1.12 and make the two objects communicate. Make use of suitable print statements to observe the dialogue. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

140 140 How Functions Are Called Using Pointers ? Suppose we have a function with signature double f_1 (int, char, double); A pointer to this function is declared as follows: double (*pointer) (int, char, double); pointer = f_1; The general form of declaration is: return_type(*name)(list_of_param_types); Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

141 141 Functions Calls Using Pointers (cont) The pointer can point to a function only if their signatures match, ie both must have identical return_type and list_of_param_types. The pointer_name must be preceded with * and enclosed within parenthesis. Without the parenthesis the above declaration has a completely different semantic: double *pointer (int, char, double); Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

142 142 Functions Calls Using Pointers (cont) double *pointer (int, char, double); The above means there is a function of name pointer which takes three parameters of types int, char, double and in that order; the function returns a pointer to a variable of type double. Note “pointer” is not a pointer. To make it a pointer we must write double (*pointer) (int, char, double) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

143 143 Functions Calls Using Pointers (cont) A pointer can point to more than one function as long as their signatures are identical. This is a great advantage because the same pointer can be made to point at different functions (of identical signatures) on the fly. Similarly, an array of pointers can be declared to point at more than one functions of identical signatures as follows: Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

144 144 Functions Calls Using Pointers (cont) double do_sum(double, double); //Prototype decl. double do_mult(double, double); //Prototype decl double do_div(double, double); //Prototype decl //Array function pointers of identical signature as above declared double (*pntr[3]) (double, double) = { do_sum Then do_mult, do_div } pntr[1] (7.2, 3.5); will call do_mult(7.2, 3.5). Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

145 145 Functions Calls Using Pointers (cont) #include //Prog1.13 //Pointers to functions float do_add(float, float); //Function prototype float do_mult(float, float); //Function prototype void main() { //Pointer to function declaration float (*pointer) (float, float); //Pointer initialized with the address of function Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

146 146 Functions Calls Using Pointers (cont) ##include //Prog1.14 double do_square(double); //Function prototype double do_cube(double); //Function prototype //Function prototype double do_processing(double array[], int len, double (*pointer) (double)); void main() { double array[] = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

147 147 Close END OF CHAPTER 1 Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

148 148 Chapter 2 Mapping the Real World in Objects and Classes Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

149 149 What are Objects ? Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

150 150 Objects (cont) World around us is full of objects. Like Boeing 747, Airbus, etc are examples of Aircraft; Alsatian dog, Poodle, St Bernard etc are examples of Dog; Ford Fiesta, Honda Civic etc are examples of Automobiles. For software engineering purposes the objects must be more specific or one-off in nature. Honda Civic with VIN KX1123456ZR is an object. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

151 151 Objects (cont) St Bernard dog called Mate is an object. Boeing 747 called City-of-Birmingham is an object. In object-oriented software engineering terms without this specificity the object is no longer an object but a subclass of the base class from which its is derived. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

152 152 Objects (cont) Boeing 747, AirBus just by themselves are subclasses of base class Aircraft. Alsatian, Poodle, St Bernard are subclasses of base class Dog. Ford Fiesta, Honda Civic etc are subclasses of base class Automobiles. This concept will be introduced latter in Chapter 5 under Derivation From a Single Base Class. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

153 153 What are Classes and Objects ? Class - Human Specific instance of a class is an object. Object_1 - Jim Object_2 -Susan Object_3 - John Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

154 154 Classes and Objects (cont) Jimmy, John and Susan all have common characteristics possessed by object type we define or know as humans in contrast to those we define or know to be lizards. Therefore, human and lizards are object types or classes. Jimmy, John, Susan are instances of class human. In object oriented software engineering vocabulary, objects are instances of a class. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

155 155 What is Abstraction ? Abstraction Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

156 156 Abstraction (cont) Abstraction - It is the process of identifying key aspects of an object and ignoring the others. Key aspects are those that are important relative to purpose at hand. From the point of view of banking system a person is some one with a Name, Address, Phone number, Password, Account ID. His other characteristics like, height, weight, visible identification marks, ethnic origin are not important. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

157 157 Abstraction (cont) These aspects will be important if abstraction is done from the point of view of police record. So, in forming such abstraction we choose to ignore many aspects of the object, and select few which are important and common about the object type according to concepts and perception (ie view) we hold about it. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

158 158 Abstraction (cont) Stock Number Manufactu rer Date of manufacture Model For dealer record: Object type -- Automobile Column in the table represents a characteristic or attribute of the object type Price Color Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

159 159 Abstraction (cont) License number Model Date of manufacture Date of Registration For Govt Record: Object type -- Automobile Column in the table represents a characteristic or attribute of the object type Manu facturer OwnerVIN Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

160 160 Abstraction (cont) Address For Govt Record: Object type -- Automobile_Owner Column in the table represents a characteristic or attribute of the object type Owner Name Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

161 161 Abstraction (cont) License number Model Date of manufacture Mileage For Garage Record: Object type -- Automobile Column in the table represents a characteristic or attribute of the object type Manu facturer OwnerVIN Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

162 162 Abstraction (cont) Address For Garage Record: Object type -- Automobile_Owner Column in the table represents a characteristic or attribute of the object type Owner Name Account balance Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

163 163 What is Relationship ? There is relationship between object types. In the above examples Owner’s Name appears in both Automobile and Automobile_ Owner object type. The name of the relationship is OWNS: Automobile owner OWNS Automobile. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

164 164 Relationship (cont) Information Model describes -- object types, -- attributes of those object types, and -- relationships between object types which are of interest for the given problem. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

165 165 What is a Class ? A class is an abstraction of a set of real- world things such that: -- all real-world things in the set, the objects, have the same characteristics or attributes when viewed from the same perspective, view or concept; -- all objects must follow the same rules and conform to these rules. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

166 166 Class (cont) All have the same characteristics -- means there are no vacant positions or gaps in the table. Also, there are no funny elements which does not make any sense. As for example in the Automobile object type above under Date of Manufacture column an entry like Alsatian or Boeing747 makes no sense. Similarly, under Manufacturer a vacant position is not acceptable. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

167 167 Class (cont) All follow the same rule -- automobiles turns can turn right, left, reverse and stop. So operations like turn_right(), turn_left(), reverse() and stop() can be encapsulated in the definition of the object type. Now, if an entry under the manufacturer column is empty then asking this object to fly by including operation fly() is not acceptable. Automobiles, no matter what instance it is, it cannot fly. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

168 168 Class (cont) In this discussion classes are object types, class instances are objects themselves, column headings are attributes of the class, and the table entries are specific values to the class attributes defining a particular class object or instance. Operations are simple functions which operate on the object data or class attribute values. They must be simple to define, easy to understand and easy to get it right. They Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

169 169 How to Identify Classes ? are encapsulated in the class along with the attributes via class definition. Look for things in the problem domain. Most things are of the following types. -- Tangable things. They are the easiest classes to find eg aeroplane, book, nuclear reactor, sensor, aero or fluid dynamic control surface, magnet, power supply, vehicle, valve, controller, window, button, scroll bar, icon, font, bitmap, menu, Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

170 170 Identification of Classes (cont) histogram, waveform and bitmap. -- Roles Played by Individuals or supervisor, client, employee, employer, broker, agent etc. Frequently, several role objects having strong affinity towards each other appear together in a problem description. -- Incidents. The occurrence of an event is represented by Incident Classes viz system crash, distress call, flight, accident, Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

171 171 Identification of Classes (cont) error_log, performance, service call and the like. -- Interactions. Interaction classes relates or binds more than one other classes (usually two), and are of contractual or transactional in flavor. Class marriage binds two other classes man and a woman. Class purchase relates to three other classes buyer, seller and purchase_receipt. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

172 172 Identification of Classes (cont) -- Specification. Specification classes usually appear in the manufacturing or inventory domain.The essence is to abstract and encapsulate description and engineering data. The specification classes need not be tangible. They may be conceptual, ie specification class Policy Types or its subclasses Life Insurance Policy, Automobile Insurance Policy etc. Other examples of conceptual type specification classes are account, queue, stack etc. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

173 173 Identification of Classes (cont) Model no Height ft Breadth ft Length ft Power HP MK121 2115 Voltage Volt 200 MK25032215 415 The Specification -- What it means to be model MK250. class ElectricMotor Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

174 174 Identification of Classes (cont) A specification class usually has a complementary instance class. Serial no Model no Present location 12345 At milling station no 2. MK121 54321At room 5 driving compressor no 3.MK250 Instance class objects (instances) that meet the specification. class ElectricMotorUsage Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

175 175 How to Name Classes ? Usually used names ie commonly used names. TrafficSignalingIndicator -- Not a good name. TrafficLight -- A much better name. ExpertInHealthMatters -- Not a good name. Doctor -- A much better name. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

176 176 Naming Classes (cont) Strong regularly used words with extended meaning are preferred to vague, esoteric or unnecessarily technical words. ColdEnvironment -- Not a good name. Refrigerator -- A much better name. ObstacleCrossingDevice -- Not a good name. Bridge -- A much better name. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

177 177 Naming of Classes (cont) Names contrasting in the same dimension should be used. HighVoltagePowerSupply -- Not Ok ContinuousPowerSupply PulsedPowerSupply -- Good choice ContinuousPowerSupply Precise names should be used. If the commonly used names are short, adjectives should be used to make the name more Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

178 178 Naming of Classes (cont) meaningful. Room -- Acceptable CleanRoom -- Better ColdRoom -- Better Names based on essential nature should be used instead of usual customary but less meaningful names. Buffer -- Ok ArnicTransmitBuffer -- Better Queue -- Ok Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

179 179 Naming of Classes (cont) UartReceiveQueue -- Better CommandResponseQueue -- Better Content based names should be used. Person legally entitled to operate. Operator’sLicense -- Bad LicensedOperator -- Good Words which have different meaning to different domains should be avoided. State, Account, Operation, Schedule, Order, Task, Form, Part, Action, Assembly Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

180 180 What is an Attribute ? and the like. An attribute is the abstraction of a single characteristic possessed by a set of objects which themselves have been abstracted by defining or postulating an object type or class. The set of attributes of a class -- must be complete to capture all characteristic of the objects relevant to the context; -- fully factored ie each attribute fully Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

181 181 Attributes (cont) captures a separate property of the class abstracted; and -- mutually orthogonal ie the attributes have nothing in common. They take values independently of one another. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

182 182 Attributes (cont) Notations UartDeviceConfig baud_ rate word_ length parity loop_back _enable receiver_ enable data_received _threshold …. Empty table Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

183 183 Attributes (cont) Graphical form UartDeviceConfig baud_rate word_length parity loop_back_enable receiver_enable data_received_threshhold interrupt_on_tx_buffer_em ptyoverrun_count Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

184 184 Attributes (cont) UartDeviceConfig ( baud_rate, word_length, parity, loop_back_enable, receiver_enable, data_received_threshold, interrupt_on_tx_buffer_empty, overrun_count ) Textual form Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

185 185 What are Descriptive Attributes ? Descriptive attributes contain intrinsic facts about each instance of a class. WindSpeedSensor wind_speed_sensor_ID speed_reading calibration_constant auto_pilot_# (R) wind_speed_sensor_name calibrate() get_value() Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

186 186 Descriptive Attributes (cont) The speed_reading of WindSpeedSensor S1234 is 700. The calibration_constant of WindSpeedSensor S1234 is 2.5 km/hour. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

187 187 Descriptive Attributes (cont) ControlSurface control_surface_ID x_position y_position auto_pilot_# (R) set_posxy() Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

188 188 Descriptive Attributes (cont) The x_position of ControlSurface CS4321 is 2 m. The y_position of ControlSurface CS4321 is 1 m. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

189 189 Descriptive Attributes (cont) NorthSectorValve north_sector_valve_ID desired_state current_state controller_# (R) open() close() Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

190 190 Descriptive Attributes (cont) The desired_state of NorthSectorValve VNS4321 is OPEN. The current_state of NorthSectorValve VNS4321 is CLOSED. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

191 191 Descriptive Attributes (cont) Employee employee_ID salary address department (R) employee_name Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

192 192 Descriptive Attributes (cont) The salary of the employee 98765 is $5000 per month. The address of the employee 98765 is 124 Anystreet, Richmond, CA-757852 Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

193 193 What are Naming Attributes ? Naming attributes provides facts about arbitrary labels and names carried by each instance of a class. The names and labels of each object can be changed without changing anything else. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

194 194 Naming Attributes (cont) WindSpeedSensor wind_speed_sensor_ID speed_reading calibration_constant auto_pilot_# (R) wind_speed_sensor_name calibrate() get_value() Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

195 195 Naming Attributes (cont) TheWindSpeedSensor whose wind_speed_sensor_ID is S1234, and whose wind_speed_sensor_name is Terry. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

196 196 Naming Attributes (cont) NorthSectorValve calibrate() get_value() north_sector_valve_ID desired_state current_state controller_# (R) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

197 197 Naming Attributes (cont) NorthSectorValve whose north_sector_valve_ID is VNS4321. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

198 198 Naming Attributes (cont) Glider aircraft_ID altitude latitude longitude pilot_license_#(R) name Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

199 199 Naming Attributes (cont) The glider whose aircraft_ID is ZY4321, and whose name is Wind_Surfer. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

200 200 Naming Attributes (cont) Employee employee_ID address salary department (R) employee_name Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

201 201 Naming Attributes (cont) The employee whose employee_ID is Z98754. His name is Joe_Bloggs. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

202 202 What are Referential Attributes ? A referential attribute ties an instance of one class with an instance of another class. Such attributes are also known in the literature as handles, access keys or qualifiers. They are special attributes of a class to manage access. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

203 203 Referential Attributes (cont) CreditCard Account Customer name address phone password account_ID (R) account _ID balance pin (R) account_ID query() credit($: x) debit($: y) pin withdrawal_l imit pin balance transaction() Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

204 204 Close END OF CHAPTER 2 Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

205 205 Chapter 3 Constructors for C++ Objects Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

206 206 How Constructors Initialize Class Object ? An alternative style is shown below. class A { int i, j; double b, c; public: //Declare constructor prototype A( int xi = 10, int xj = 20, double xb = 0.0, double xc = 0.0) ; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

207 207 Constructors Initialize Class Object (cont) ………. }; Next define the constructor as follows: A::A(int xi, int xj, double xb, double xc) : i(xi), j(xj), b(xb), c(xc) { } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

208 208 Constructors Initialize Class Object (cont) In above note the empty body of the constructor { }. i(xi), j(xj), b(xb), c(xc) is known as the initializer list. The initializer list is processed before the body of its constructor. The order of items in the list are irrelevant. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

209 209 Constructors Initialize Class Object (cont) Member data objects are initialized in the order they appear in the class definition. Valid constructor calls are as follows. -- A a_obj(1,2); -- A aa_obj(5, 7, 48.2); Containment of other class objects can also be handled through initializer list. This will be discussed later. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

210 210 What are Storage Class Specifiers ? They are auto, register, static and extern. They are used with class object declaration for a number of reasons. auto - applicable only to objects declared with block scope. This type of object is created on the system stack. It gets automatically destroyed when the block is exited, or the function declaring the object returns to the caller. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

211 211 Storage Class Specifiers (cont) Local objects are objects declared with block scope. They have auto duration by default. register - also applicable only to objects declared with block scope. It indicates that the object is frequently used, and is a request (not an order) to the compiler to place the object in a hardware register. The compiler is, however, at liberty not to pay any attention to the request. Unlike C use of address-of operator & on Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

212 212 Storage Class Specifiers (cont) a register object is legal. Specifying a class member data object to be auto or register in a global class definition is illegal; however, a whole class object can be specified to be auto. static - A static class member is shared by all instances of its class. Unlike a usual class member, it is not part of a particular object. A static data member must be defined outside the global class definition, Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

213 213 Storage Class Specifiers (cont) and attached to the class by the scope resolution operator. For this the class name and the scope resolution operator :: has to be used to identify which class the static data identifier belongs to. Thus, the definition of a static data member of a class outside the global class definition directs the compiler to allocate space for the data object and to initialize it at the start of program execution. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

214 214 Storage Class Specifiers (cont) #include //Prog3.1A class Rudder { class HydraulicMotor { double force; public: HydraulicMotor() { force = 2000.0; } void DisplayMotorData() { cout << "HydraulicMotor exerts " Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

215 215 Storage Class Specifiers (cont) Constructors should not be used for initialization of static attributes. They are, however, allowed to modify static data. Constructor and destructor functions must never be declared static. Both ordinary and static member functions can handle static data. But a static function can only use static data with or without reference to a particular object. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

216 216 Storage Class Specifiers (cont) Applicable to objects declared within block scope, or objects and functions within a global class definition, or file scope. But not applicable to the class definition itself. Global objects are objects declared with file scope. They have static duration by default ie they last for the entire duration of program execution. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

217 217 Storage Class Specifiers (cont) #include // Prog 3.1 enum Bool { FALSE, TRUE }; class ExecutiveTasks { public: static Bool start_test; //Declaration }; Bool ExecutiveTasks::start_test = TRUE; //Definition and initialization void main() { //Compiler generated constructor invoked. Accessing Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

218 218 Storage Class Specifiers (cont) Exercise Prog3.1 Compile and run Prog3.1 and comment on the behavior. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

219 219 Storage Class Specifiers (cont) Static data members of a class are not part of any object instantiated using the class. Thus, use of static data members can reduce the size of objects. Hence, static data members of a class cannot be initialized through object creation. They must be initialized directly somewhere in the program outside the global class definition. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

220 220 Storage Class Specifiers (cont) This also means that a static data member of a class is available to a program without the need for instantiating the class. It would appear that a static data member is just another global variable. But this is not so. Global data object can get corrupted easily through uncontrolled access. Their use is not considered to be a good programming practice. Further, C++ objects consume large amount of memory. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

221 221 Storage Class Specifiers (cont) Use of large number of global C++ objects will increase the size of the executable. A static data member of a class obeys the access rules like any other data members of the class. Thus, it is safer to use static data members in a class when several objects of that class needs to communicate with each other. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

222 222 Storage Class Specifiers (cont) A function prototype in a global class definition can also be specified to be static. This allows the function to be accessed directly using the class name and the scope resolution operator :: without the need for an object instantiated using the class. extern - entire class objects can be so declared, but not individual features (attributes and functions) of a class. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

223 223 Storage Class Specifiers (cont) File_1.c //Function prototype. The function can be called from within this file only. static void func(int j, double x); //Fixed location in memory. Cannot be accessed in any other file using //keyword extern. static int i; // Fixed location in memory. Can by accessed in another file using //keyword extern. int jj; int k = 5; // Same as jj above, and the variable is initialized. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

224 224 Storage Class Specifiers (cont) File_1.c // string in a fixed location in memory, containing the address of another //fixed memory location where “Hello World” is stored. char* string = “Hello World”; void* ptr; //Fixed location in memory. //All the above variables are visible and accessible to codes below. Such //variables are called global variables. Once created they exist in the //RAM throughout the duration of execution of the program. void func( int xi, double* pointer ) { //xi on stack; pointer on stack static int l; //Fixed location in memory. int m; // On stack. //Variables xi, pointer, l and m are NOT …………. //available outside the function scope. ………….. } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

225 225 Storage Class Specifiers (cont) File_1.c All the global variables above are shared between tasks calling func() or any other function below. Thus in a multitasking environment the global variables are shared, and BEWARE a task may corrupt them. Use SEMAPHORE or DISABLE interrupts when entering CRITICAL sections of the code. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

226 226 Storage Class Specifiers (cont) File_1.c Function parameter ‘xi’ -- In multitasking environment each task has its own stack on which xi will be located. So xi is incorruptible. Function parameter ‘pointer’ -- If all tasks send different address to pointer the all is well. If, however, two tasks send the same address to pointer, then one task can corrupt the shared data. BEWARE !! Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

227 227 What are Arbitrary Duration Class Objects ? Local objects defined within a block are automatically destroyed when the block is exited. Such objects are transient. Hence, they take up memory only as long as they exist. Global objects persist for the entire duration of the program execution. Static objects also exist for the entire duration of the program execution. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

228 228 Arbitrary Duration Class Objects (cont) Arbitrary duration class objects are created by the new operator, and once created they persist for the entire duration of the program execution until explicitly destroyed using the delete operator. Arbitrary duration class objects have the advantage that they are dynamically created when needed, thus avoiding the disadvantage of inflated executable size resulting from the usage of Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

229 229 Arbitrary Duration Class Objects (cont) global or static objects. Usage of static class data member objects reduce the size of the entire object, an thus reducing the size of the executable when several objects of the same class are used in the program. Their usage is a step towards the reduction of executable size, but maximum reduction occurs when objects of arbitrary duration are used for reasons mentioned above. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

230 230 What are the Properties of Constructor Functions ? It is illegal for any constructor operation, default or overloaded, to have any return value. It is common to provide several overloaded constructor functions. Each version must have explicitly different types of arguments. Copy constructor allows an object of the class to be declared, and then initialized with the contents of another class object. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

231 231 Properties of Constructor Functions (cont) A constructor function of a class is able to freely call other member functions of that class which can modify the class member data objects. A constructor function must initialize all class data objects including pointer data members to legal starting values. Uninitialized pointer spells disaster. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

232 232 Properties of Constructor Functions (cont) A constructor function is allowed to freely call any function belonging to a library in the compiler. For this correct header file needs to be included in the source program calling the function. A constructor can be invoked directly. A constructor can also be used to convert another basic (char, integer, double etc) data type to the enclosing class type -- type Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

233 233 Properties of Constructor Functions (cont) conversion. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

234 234 Properties of Constructor Functions (cont) #include // Prog3.2 class Watchdog { int number_of_strobes_since_time_out; //Attribute //private by default public: Watchdog() { number_of_strobes_since_time_out = 1; } //Default constr Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

235 235 Properties of Constructor Functions (cont) Exercise Prog3.2 Compile and run Prog3.2. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

236 236 What is an Initializer List for an Array of Objects ? An array of objects can be initialized through an initializer list. A object_array[5] = { A(5); A(10); A(20) } There are five elements in the array, but the list contains only three entries. The compiler interprets the above as: A object_array[5] = { A(5); A(10); A(20); A(); A(); } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

237 237 Initializer List (cont) object_array[0] contains object A(5) object_array[1] contains object A(10) object_array[2] contains object A(20) The above three objects are created by type conversion; and the two below by the default constructor. object_array[3] contains object A() object_array[5] contains object A() Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

238 238 What is overloading of Constructor Functions ? It is common to provide several overloaded constructor functions. Each version must have explicitly different types of arguments or signature. Copy constructor allows an object of the class to be declared, and then initialized. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

239 239 Overloading Constructor (cont) #include // Prog3.3 class FuelSystem { //Attribute private by default double wf_cmd, grv_at_max, grv_at_95; public: //Constr 1 -- default FuelSystem( double = 1.1, double = 2.2, double = 3.3); //constr 2 FuelSystem(int, int, int); Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

240 240 How to use Destructor ? #include // Prog3.6 #include class Display { char description[41]; int unit_num; public: Display( int = 0, char* = "" ); ~Display() { cout << "Destructor called." << endl; } void display(); }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

241 241 How to use Destructor ? void main() { //Prog3.7 { Display theRemoteDisplay( 1, "Remote Display" ); theRemoteDisplay.display(); } //Destructor //called automatically when block scope is exited. // theRemoteDisplay.display(); //Check whether // the object is truly destroyed. Display theRemoteDisplay( 2, "same theRemoteDisplay object instantiated second time" ); theRemoteDisplay.display(); } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

242 242 Usage of Destructor (cont) Destructor should not be called explicitly as shown below: obj_name.class_name::~class_name(); Compiler will not complain about the above statement. The destructor function will execute, but the object will still exist. The compiler will flag an error if an object of the same name is tried to be created after the call to the destructor. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

243 243 Usage of Destructor (cont) The only way to destroy an object is to define it in a block scope. The destructor will be called automatically when the block scope is exited. The object will get destroyed, and another object of the same name can be created outside the block scope. All the above lead to the following statement: “ALTHOUGH DESTRUCTOR FUNCTION CAN BE CALLED Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

244 244 Usage of Destructor (cont) EXPLICITLY, IT WILL NOT DESTROY THE ATTACHED OBJECT. DO NOT CALL DESTRUCTORS EXPLICITLY”. If you do not declare a destructor in the global class definition ( ie header file class_name.h), then the compiler will automatically generate one for you. If, however, you have acquired some memory in the heap (free store) using the operator new, then you must explicitly Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

245 245 Usage of Destructor (cont) declare a destructor in the global class definition. In the definition of the destructor you must delete this dynamically acquired memory, in the heap, using the operator delete, otherwise memory leak would occur. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

246 246 Usage of Destructor (cont) #include //Prog3.8 #include class Catalog { char name[30]; public: Catalog(char* ptr) { strcpy(name, ptr); }; void display() { cout<< name << endl; } ~Catalog() { cout << "Destructor called." << endl; } }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

247 247 Usage of Destructor (cont) #include //Prog3.9 #include class Customer { char* ptr; public: Customer(char* xname) { ptr = new char[80]; strcpy(ptr, xname); } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

248 248 Usage of Destructor (cont) Exercise Prog 3.10 When program Prog3.9 is executed an error message is displayed. Explain the reason for this error message, and modify the program such that this error message is no longer displayed. Next create an object of the same name as before, and incorporate the display() function. Compile and execute the modified program. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

249 249 Overloading Constructor (cont) Exercise Prog 3.11 For copyright reasons it is not possible to include program LIFO here. A personal copy is available which may be borrowed. Study the program, and in difficulty assistance will be provided. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

250 250 Defining Local (auto) Class Objects Exercise Prog 3.12 The following diagram shows class dbllist representing a doubly-linked-list. The next is a sequence diagram showing communications between the main program, and the object thedbllist instantiated from the class. Develop a working C++ program. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

251 251 Defining Local (auto) Class Objects (cont) Exercise Progs 3.11 & 3.12 The problems have been taken from: Perry, Paul J et al :’Using Borland C++4’, Special Edition, Que, 1994, ISBN 1-56529- 304-5. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

252 252 Defining Local (auto) Class Objects (cont) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

253 253 Defining Local (auto) Class Objects (cont) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

254 254 Defining Local (auto) Class Objects (cont) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

255 255 Defining Global Class Objects Exercise Prog 3.13 For copyright reasons it is not possible to include program DIR here. A personal copy is available which may be borrowed. Study the program, and in difficulty assistance will be provided. Ref: Same as Exercise Progs 3.11 & 3.12. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

256 256 Close END OF CHAPTER 3 Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

257 257 Chapter 4 Communication Between C++ Objects Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

258 258 How :: is Used for Access ? A global variable or a function in file scope can become hidden by an identical member name in a class definition. Scope resolution operator :: can be used to access the global name from within the class. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

259 259 Use of :: for Access (cont) #include // Prog 4.1 double air_pressure =10.5; class AirDataComputer { //Attribute private by default double air_pressure; public: //Default constructor AirDataComputer() { air_pressure = 20.8; } void display() { cout << "Class air pressure = " << air_pressure << endl; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

260 260 Use of :: for Access (cont) cout << "Global air pressure = " <<::air_pressure << endl; } }; // void main() { AirDataComputer airdatacomputer; //Default constructor invoked airdatacomputer.display(); } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

261 261 Use of :: for Access (cont) Inside the class definition the class member data object air_pressure hides the global data object air_pressure. The way to access this global data object is by qualifying it by the class resolution operator ::. Exercise Prog4.1 Verify the truth of the statement made in Prog4.1 by compiling and running a program. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

262 262 Use of :: for Access (cont) #include // Prog4.2 class CockPitDisplay { public: static int channel_number; public: //Default constructor CockPitDisplay() { channel_number = 1; } //Overloaded constructor CockPitDisplay(int x) { channel_number = x; } void display() { cout << "Channel number = " << Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

263 263 Use of :: for Access (cont) Exercise Prog4.2 Run the above Prog4.2 and explain its behaviour. Comment out int CockPitDisplay::Channel_number, and run the program again. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

264 264 What are C++ Scope Rules ? C++ scoping rules follow the ANSI C rules except for classes and class objects, and those mentioned in the list below. C++ allows a local (auto) object to be declared anywhere in the program where a C statement is legal. The following is legal in C++ but not in C. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

265 265 C++ Scope Rules (cont) void func() { int j = 10; //Valid for both C++ and C. int i; //Valid for both C++ and C. for (i = 0; i < 5; ++i) { --j; } int m = 0 ; //Valid for C++ but not for C. for (i = 0; i < 5; ++i) { ++m; } } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

266 266 C++ Scope Rules (cont) C requires both local variables j and m to be defined at the top of a block. In C++ local variables can be declared anywhere inside the block. In C++ a function prototype must be declared before it can be called. In C++ it is illegal for a class data object inside the class definition to have the same name as the class. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

267 267 C++ Scope Rules (cont) class A { ……. int A; // Illegal in C++ ……. }; In C++ a data object following a class definition can block the visibility of the class to codes following the data object if it has the same name as the class. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

268 268 C++ Scope Rules (cont) class A {…. }; int A; main () { A a; // Instantiation will fail -- which A ……. } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

269 269 C++ Scope Rules (cont) main () { class A a; // Valid instantiation …… } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

270 270 C++ Scope Rules (cont) #include // Prog4.3 class IO { public: static int display() { return 100; } }; int IO = 6; void main() { IO io; //Compiler generated constructor invoked cout << io.display() << endl; } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

271 271 C++ Scope Rules (cont) Class name IO is hidden by the int IO = 6. Exercise Prog4.3 Try running Prog4.3. In main () comment out the instantiation, and run the program. Use keyword class in the instantiation, and try to run the program again. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

272 272 What is the Difference Between Reference Operator and Address- of Operator ? Reference operator generates a reference to an object in order to give an alternative name to the object. int k = 10; // A basic object k is // declared and initialized int& j = k; // j is a reference to k -- ie j //is another name for k Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

273 273 Reference Operator and Address-of Operator (cont) Address-of operator extracts the address of the memory location where an object resides from the object name. int k = 10; // A basic object k is // declared and initialized int *kk; // A pointer to an integer // object is declared kk = &k; //Address of k is extracted, and //kk is initialized to this address Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

274 274 Reference Operator and Address-of Operator (cont) Note the difference in the position of &. For reference it is on the left hand side, and for address-of it is on the right-hand side of the assignment operator =. References always binds to objects, and not to addresses. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

275 275 What are the Advantages of Using Reference? Use of a reference allows manipulation of a class object inside a function without actually copying it in another object. A a; B b; ………... func( a, b); //Function called ………….. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

276 276 Advantages of Using Reference (cont) //Function definition void func(A& aa, B& bb) { …….. } Using the following function definition will cause class objects a and b to be copied in aa and bb respectively before any computation is done. Copying takes time -- thus, the process is computing wise inefficient. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

277 277 Advantages of Using Reference (cont) void func(A aa, B bb) { …….. } Reference can also be used to return a class object without physically copying it. A a; B b; C& C::func(A& a, B& b); Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

278 278 Advantages of Using Reference (cont) #include // Prog4.4 class ControlPanel { public: double demanded_speed; public: //Default constructor ControlPanel() { demanded_speed = 1500.0; } //Function prototype -- declaration friend void modify(ControlPanel); Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

279 279 Advantages of Using Reference (cont) Object controlpanel is copied into object obj_controlpanel in the function definition of modify(ControlPanel obj_controlpanel), and placed in the stack. Only this copy in the stack is modified, and not the original object. When the function returns the object gets destroyed automatically. This original object controlpanel then gets printed. If a reference to the object Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

280 280 Advantages of Using Reference (cont) controlpanel is passed on to the function definition by using void modify(ControlPanel& obj_controlpanel) { …… } then a copy obj_controlpanel of the entire object is not placed in the stack. Now obj_controlpanel is a reference to the originally created controlpanel, and this original object gets modified resulting in the Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

281 281 Advantages of Using Reference (cont) correct print out. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

282 282 Advantages of Using Reference (cont) #include // Prog 4. 5 class ControlPanel { public: double demanded_speed; public: //Default constructor ControlPanel() { demanded_speed = 1500.0; } //Function prototype -- declaration. Note reference to //the object in the argument Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

283 283 Advantages of Using Reference (cont) Exercise Prog4.4 & Prog4.5 Compile and run the two programs Prog4.4 and Prog4.5 Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

284 284 What are the Restrictions on Reference ? A reference must be bound to an object before it can be manipulated, ie it cannot be manipulated directly. This is the only restri. int& j; ++j; // Illegal int i = 1; int& j = i; // Reference j is now bound to i ++j; // i is now 2 Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

285 285 How Objects are Used ? Declaration of a class must precede before reference can be made to an object of this class. To circumvent the problem, an incomplete forward definition of the class is allowed. Incomplete forward definition of a class is synonymous to forward declaration of a class. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

286 286 Use of Objects (cont) #include // Prog4.6 //Class Display is forward declared because //reference will be made shortly to an object of //this class before the class can be fully declared. class Display; class Alarm{ public: int fault_severity; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

287 287 Use of Objects (cont) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

288 288 Communication Between Objects Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

289 289 Communication Between Objects Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

290 290 Use of Objects (cont) #include // Figure 4.7 //class ServoDrive is forward declared because //reference will be made shortly to an object of //this class before the class can be fully declared. class ServoDrive; class FlightComputer{ private: double rudder_position; public: Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

291 291 Use of Objects (cont) A class member function is allowed to declare (create) and use a local object of a class type declared and completely defined outside the function definition. A class member function is also allowed to create (declare) and use an object of its own class type. This is legal because member functions are invoked on behalf of a class instance (object), and not on behalf of the class itself. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

292 292 Use of Objects (cont) This means that the local object so created is a completely different object than the object on whose behalf the constructor was called. Both objects are now two completely separate and independent instances of the same class. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

293 293 What is a Friend Class ? In the global definition of a class another class can be declared a friend of this containing class. This makes all member functions of the contained class to be available as friends of the containing class. class A { …… }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

294 294 Friend Class (cont) class B { …………. //All member functions of class A are //friends of the containing class B friend A; …………. }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

295 295 Friend Class (cont) Forward declaration of a class name only is sufficient for it to be introduced as a friend in an enclosing class. It is illegal for a member function body to refer to any part of another class not, as yet, defined. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

296 296 When to Use Pointer ? Pointer is the only way to access data members of an arbitrary duration class object created on the free store or heap by the new operator. This can be achieved directly using the pointer operator ->, or indirectly by dereferencing the pointer first and then using the dot operator. Pointer operator is also used to access polymorphic operations through dynamic binding of derived class objects. This will be fully discussed in Chapter 7. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

297 297 Using a Pointer (cont) #include // Prog 4.8 #include class employee { char surname[30]; char first_name[30]; char middle; char ssn[12]; int hours; public: Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

298 298 Using a Pointer (cont) Exercise Prog4.8 Compile and run Program 4.8 Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

299 299 How are Pointers Used to Point to Class Members ? #include // Prog 4.9 class FaultManager { int location; public: FaultManager(int k) : location(k) { } int what_location() { return location; } void what_location(int k) { location = k; } }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

300 300 Pointers Pointing to Class Members (cont) Exercise Prog4.9 Compile and run the above program and explain its behavior. Put a space between ‘.*’ and ‘->*’, compile and run the program. Explain its behavior. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

301 301 How Bidirectional Communication Implemented ? Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

302 302 Bidirectional Communication (cont) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

303 303 Bidirectional Communication (cont) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

304 304 Bidirectional Communication (cont) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

305 305 Bidirectional Communication (cont) #include //Prog4.10 #include enum { OPEN, CLOSED }; class Operator; class Valve { private: char name[30]; bool valve_status; Operator *theOperator; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

306 306 How to Declare Array of Pointers to Objects ? Simply declare an array of pointers to objects of class type. main() { int i; employee *ghani[5] // An array of 5 pointers. //An object of class type employee is //created and the reference is assigned to a //pointer. This is repeated five times. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

307 307 Array of Pointers to Objects (cont) for (i = 0; i < 5; ++i) ghani[i]= new employee; for (i = 0; i print_it(); // Each ghani object is deleted individually. for (i = 0; i < 5; ++i) delete ghani[i]; } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

308 308 Declaring a Pointer to An Array of Objects (cont) Delete operator cannot be used to delete constant objects. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

309 309 Array of Pointers to Objects (cont) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

310 310 Array of Pointers to Objects (cont) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

311 311 Array of Pointers to Objects (cont) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

312 312 Array of Pointers to Objects (cont) #include // Prog4.11 #include enum { OPEN, CLOSED }; class Operator; class Valve { private: char name[30]; bool valve_status; public: void set_name(char* string) { strcpy(name,string); } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

313 313 How to Declare a Pointer to An Array of Objects ? Declare just one pointer of the class type. void main() { int i; employee* ghani; //Just a single pointer //Instantiate five objects of class type //employee, and put them in contiguous //array and assign the reference to the //pointer ghani Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

314 314 Declaring a Pointer to An Array of Objects (cont) ghani = new employee[5]; //Note *ghani == ghani[0]. So, pointer //operator -> not used. for(i=0; i<5; ++i) ghani[i].print_it(); // Delete five instances of employee class in //contiguous array pointed at by pointer delete [5] ghani; //ghani. } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

315 315 Declaring a Pointer to An Array of Objects (cont) A contiguous array of five class instances are created by the operator new in the free store. Default constructor is invoked by new soon after each class instances are created. A single pointer pointing at the address of the first object in the array is then returned by new. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

316 316 Declaring a Pointer to An Array of Objects (cont) Delete operator cannot be used to delete constant objects. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

317 317 Pointer to An Array of Objects (cont) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

318 318 Pointer to An Array (cont) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

319 319 Pointer to An Array of Objects (cont) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

320 320 Pointer to An Array of Objects (cont) #include //Prog4.12 #include enum { OPEN, CLOSED }; class Operator; class Valve { private: char name[30]; bool valve_status; static Operator *theOperator; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

321 321 Close END OF CHAPTER 4 Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

322 322 Chapter 5 Derivation From a Single Base Class Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

323 323 What is Type Derivation ? Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

324 324 Why Use Type Derivation ? Type derivation or inheritance is an elegant way towards code reuse. -- It allows code reuse without hacking existing code; thus preventing the possibility of introducing bugs in otherwise a good piece of code. -- The objective is to reuse existing code, with little or no modification, with a view to create new code which has additional functionality than the original reused code. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

325 325 Type Derivation (cont) Type derivation is the ability of one class to inherit attributes and operations from another class. The old class whose features (attributes and functions) have been derived is called base or parent or ancestor class. The new class is called derived or child or descendent class. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

326 326 Use of Type Derivation (cont) In procedural languages like plain C once a function or a module has been developed, it can only be used in its original form. Its functionality is not flexible, and cannot be changed except by rewriting. In object oriented languages like C++ reuse of classes is equally efficient, but with additional capability of reusing the classes in various ways flexibly without having to recode them. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

327 327 Use of Type Derivation (cont) This is called encapsulation, a property which isolates and protects code that has already passed acceptance test to qualify as library class. ways flexibly without having to recode the classes. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

328 328 What is Class Composition ? Class composition allows reuse of an existing quality class through instantiation of this class inside a user written class. -- It is one of the two ways of reusing a class. The other method is inheritance or derivation of a class from a base class. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

329 329 Class Composition (cont) #include // Prog5.1 class Generator { public: void display() {cout << "This is an generator_obj." << endl; } }; class Apu { Generator generator_obj; //Composition public: Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

330 330 Class Composition (cont) Compiler generate the constructor functions for both classes Generator & Apu. However, constructor for class Apu is executed first, and then that for class Generator. Example Prog5.1 Sketch the class and sequence diagrams for Prog5.1, and run the program. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

331 331 Class Composition (cont) The class whose object is declared inside an enclosing class must have a default constructor with default parameter values. The enclosing class’s constructor operation definition can then contain constructor initializer to pass arguments to the constructor function of the enclosed class object if so desired. If default values for the enclosed class object is to be used then a default constructor for the enclosing class has to be provided as well. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

332 332 Class Composition (cont) #include // Prog5.2 class Generator { double voltage; int i; public: Generator(double v = 100, int ii = 25) { voltage = v; i = ii;} void display() {cout << "This is a generator_obj having values ” << voltage << “ “ << i << endl; } }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

333 333 Class Composition (cont) Exercise Prog5.2 Compile and run the program Prog5.2. Recompile and run the program once again so that the default values in the constructor for the enclosed object are used. Explain the new behavior. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

334 334 Does Access Rules Change Under Composition ? Scope and access rules do not change for composite class definition. The containing class has no access to the private attributes of the contained class. Exercise Prog5.2 Show that class Apu cannot access class Generator’s private attribute voltage. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

335 335 What is So Special About Inheritance ? Inheritance allows new class, called child class to be specified by difference from an existing similar class called parent. This allows a new class to be created using a well proven existing class by adding extra attributes and behaviors as needed. The beauty of this approach is that the existing parent class requires no modification, also the new child class need not be developed Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

336 336 Advantage of Inheritance (cont) from a scratch each time. Further, if the child or subclass needs a different implementation of a behavior, one simply redefines the behavior in the child class. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

337 337 How to Inherit From a Single Base Class ? Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

338 338 Object Communication Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

339 339 Derivation from a Single Base Class (cont) #include // Prog5.3 class Sensor { public: void display() { cout << "This is a Sensor_obj" << endl; } }; class PositionSensor : public Sensor { public: void display() { cout << "This is a PositionSensor Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

340 340 Derivation from a Single Base Class (cont) Exercise Prog5.3 Sketch the class and sequence diagrams for Prog5.3, and compile and run the program. Explain the new behavior. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

341 341 Can A Friend Function be Inherited ? As a safeguard against accidental access violation, friend functions are never inherited. Such inheritance would allow access of all members of a base class, private or otherwise, accessible from a derived class. Thus, access protection is no longer available. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

342 342 How is Access Control Effected Under Default Derivation ? Access control keyword private: associated with base class members restricts their access only to functions of the base class itself. It is neither accessible to functions of the derived class, nor to non-member functions. The only way to breach this restriction is explicit declaration of friend functions Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

343 343 Access Control Under Default Derivation (cont) within the base class. The derived class member functions and non-member functions can then have access to the private members of the base class through these friend functions. Access control keyword protected: associated with base class members restricts their access only to functions of Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

344 344 Access Control Under Default Derivation (cont) the base and the derived classes. It is not accessible to non-member functions. Again, friend functions declared within the derived class may be used to circumvent this access restriction. Access control keyword public: associated with base class members allows unrestricted access by any functions within the base Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

345 345 Access Control Under Default Derivation (cont) class and the derived classes, but not to any nonmember functions under default inheritance. Under default derivation all members of the base class become private members of the derived class. They are, thus, not accessible to any non member functions. However, those members of the derived class declared public are accessible by nonmember Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

346 346 Access Control Under Default Derivation (cont) functions. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

347 347 What are Access Specifiers for Derived Classes ? Access specifiers, private, protected and public for the derived class are introduced in the following way. class base { …… }; class derived : access_specifier base { …….. }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

348 348 Access Specifiers for Derived Classes (cont) The class members maps as follows. Base class declared public Base Class Derived Class Public -> Public Protected -> Protected Private -> Not accessible Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

349 349 Access Specifiers for Derived Classes (cont) Base class declared protected Base Class Derived Class Public -> Protected Protected -> Protected Private -> Not accessible Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

350 350 Access Specifiers for Derived Classes (cont) Base class declared private (default) Base Class Derived Class Public -> Private Protected -> Private Private -> Not accessible Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

351 351 Access Specifiers for Derived Classes (cont) #include // Prog5.4 int channel_number = 0; //Global data object class Sensor { protected: int channel_number; //Class Sensor data object public: Sensor() { channel_number = 100; } }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

352 352 Access Specifiers for Derived Classes (cont) deriv_obj.display() tries to access variable channel_number. Despite visibility of global channel_number, it is not accessed immediately. Every C++ class has its own scope or namespace. Accessing process begins with searching local scope, namespace PositionSensor, first for the identifier channel_number. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

353 353 Access Specifiers for Derived Classes (cont) Since no such identifier exists in the namespace, and class Sensor is inherited by class PositionSensor with public access specifier, the name space Sensor is next searched. Such a variable is found to be a private attribute. Hence, Sensor::channel_number cannot be accessed by the member function of the derived Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

354 354 Access Specifiers for Derived Classes (cont) class PositionSensor. Complier flags an error message. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

355 355 Access Specifiers for Derived Classes (cont) Exercise Prog5.4 Sketch the class and sequence diagrams for Prog5.4. Compile and run the program. Use different access specifiers for the base class attribute, and explain the results. Use different access specifiers for derived classes and explain the results. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

356 356 Access Specifiers for Derived Classes (cont) #include //Prog5.5 class Controller { protected: double demanded_output; //Class Controller data object double actual_output; public: Controller() { Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

357 357 Access Specifiers for Derived Classes (cont) Exercise Prog5.5 Sketch the class and sequence diagrams for Prog5.5. Compile and run the program. Use different access specifiers for the base class attribute, and explain the results. Use different access specifiers for derived class and explain the results. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

358 358 How Scope Resolution Operator :: Used for Resolving Ambiguity ? To resolve identical member names in two or more classes use class_name::member_name For global variable or function name use ::object_name Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

359 359 Resolving Ambiguity Using :: (cont) #include //Prog5.6 class LogicalDevice { public: int device_id; public: void display() { cout << "class LogicalDevice has device id = ” << device_id << endl; } }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

360 360 Resolving Ambiguity Using :: (cont) Exercise Prog5.6 Sketch the class diagram and the sequence diagram. Compile and run the program as it is, and explain the behavior. Experiment with various access control specifier for class members, and explain the behavior. Experiment with various access control specifiers associated with class inheritance, and explain the behavior. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

361 361 What is Pointer “this” ? #include class PulseWidthModulation { private: int pwm_device_configuration; //Member attribute - base data object public: PulseWidthModulation() { pwm_device_configuration = 37; } //Constructor function Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

362 362 Pointer “this” (cont) //Return for this object the value of the attribute //pwm_device_configuration. //This object is explicitly pointed to by the pointer //"this". However, the pointer "this" need not be //stated explicitly. The compiler automatically takes //care of this. So, this - > can be omitted from the //class definition. int fetch() { return this ->pwm_device_configuration; } }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

363 363 Pointer “this” (cont) void main() { PulseWidthModulation pwm; //Create an instance //pwm of type class PulseWidthModulation. cout << " pwm_device_configuration = " << pwm.fetch() << endl; } A hidden constant pointer called “this” invisibly appears as the first argument for any normal member function of a class. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

364 364 Pointer “this” (cont) The pointer “this” points to the object for which any normal function is invoked. In the above example pointer “this” points to the object “pwm” for which the function “fetch()” was invoked by the statement “pwm.fetch(this)” in the main program. This allows the correct object attribute “pwm_device_configuration to be returned. The compiler handles the “this” pointer entirely behind the scenes. The programmer Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

365 365 Pointer “this” (cont) need not declare “this”. It should not be initialized, and normally no address values should be placed in it. The compiler automatically generates the necessary code, invisibly, to do all the necessary work before a member function executes. A class member function makes use of “this” pointer in a completely transparent manner. In plain C a structure pointer operator -> must be used to access a Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

366 366 Pointer “this” (cont) member data object if a pointer is used to point at the structure. With C++ compiler it is neither necessary to use the class or structure name as a prefix to a member name, nor there is a need for a pointer to point at a particular member data object in lieu. All instance objects and their member data are distinguished individually by the compiler via this invisible pointer “this”. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

367 367 Pointer “this” (cont) There are occasions, however, when the pointer “this” needs to be used explicitly. Behavior of operator = under derivation, in Programs 5.7 and 5.8, illustrates this. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

368 368 How Does Operator = Behave Under Derivation ? A_base class operator = will serve A_base class objects well. Problem will arise if a derived class B_derived is defined along similar lines, as given below. In this class the operator = does not copy the base class subobjects data members. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

369 369 Behavior of Operator = Under Derivation (cont) #include //Prog5.7 class PhysicalDevice { //Attributes private by default int qsm_vector_offset, tpu_vector_offset; public: //Default constructor PhysicalDevice(int x = 10,int y = 100) { qsm_vector_offset = x; tpu_vector_offset = y; } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

370 370 Behavior of Operator = Under Derivation (cont) When the main function copies one derived class PhysicalSim object into another, the base class subobject members are not copied. So, when display() is executed it shows the base class subobject data members to be still 0, 0. Modifications for avoiding this slicing copy operation are as follows: Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

371 371 Behavior of Operator = Under Derivation (cont) #include // Prog 5.8 class PhysicalDevice { //Attributes private by default int qsm_vector_offset, tpu_vector_offset; public: //Default constructor PhysicalDevice(int x = 10,int y = 100) { qsm_vector_offset = x; tpu_vector_offset = y; } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

372 372 Behavior of Operator = Under Derivation (cont) The “this” pointer pointing to derived class PhysicalSim object is converted explicitly (recast) to a pointer of base class PhysicalDevice type. The value of the converted “this” is next assigned to another pointer base_ptr defined to be of base type PhysicalDevice. The base class PhysicalDevice operator = is next forced by having the left hand side of = Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

373 373 Behavior of Operator = Under Derivation (cont) to be of the base class type *base_ptr = deriv_obj; This usage is legal if the base class is inherited using public access declaration. Alternative solution to the copy slicing problem is to form base class pointer to both sending and receiving objects. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

374 374 Behavior of Operator = Under Derivation (cont) A_base *a_ptr1, *a_ptr2; //Pntr to A_base //class ……. a_ptr1 = (A_base*)this; //Receiving object a_ptr2 = (A_base*) &b_obj; //Sending object *a_ptr1 = *a_ptr2; //Invoke A_base op = Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

375 375 Behavior of Operator = Under Derivation (cont) Exercise Prog5.7 & Prog5.8 Draw the class diagram and the sequence diagram for Prog5.7 & Prog5.8. Compile, run the programs and critically examine their behavior. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

376 376 Close END OF CHAPTER 5 Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

377 377 Chapter 6 Multiple Inheritance Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

378 378 Class Diagram Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

379 379 Close END OF CHAPTER 6 Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

380 380 Chapter 7 Polymorphism & Dynamic Binding Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

381 381 What is Polymorphism ? Polymorphism is the ability of a programming language for describing the behavior of a function without depending on its parameters. In object-oriented language the concept of polymorphism extends to many forms of a class as though they are one. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

382 382 How is Polymorphism Supported ? ADHOC -- Overloading of operations is a way to impart a sort of polymorphism or different behaviors to different objects using the same function name. -- Different classes containing functions having identical name, say print_it(), is also another sort of polymorphism. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

383 383 Support for Polymorphism (cont) TEMPLATE CLASSES -- Parameterized classes have parameters supplied during compile time to create distinct versions of the class. All these versions will have identical function names yet exhibit distinct behaviors or polymorphic behavior. STATIC STRUCTURAL POLY- MORPHISM -- This type of polymorphism is present in any type of class hierarchies generated through the Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

384 384 Support for Polymorphism (cont) inheritance mechanism. All the above three types of polymorphism involve static binding resolved during compile time. STRUCTURAL POLYMORPHISM VIA DYNAMIC BINDING -- This type of polymorphism uses function overriding, pointers and references to class objects. It is implemented using virtual functions in the class hierarchies, and is resolved during Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

385 385 Support for Polymorphism (cont) run-time. Selection of actual function is done during run-time, and this is called dynamic or late binding. This is the real polymorphism, and one of the great strengths of object oriented programming paradigm. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

386 386 What are Virtual Functions ? Polymorphic functions have identical names, and are implemented in the derived classes by declaring a function having the same name in a base class to be virtual. Virtual functions provide a “pass through feature”. If a pointer declared the base class type is dynamically bound to a derived class object, and a polymorphic function is called the corresponding virtual function of the base class will not be invoked. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

387 387 Virtual Functions (cont) Correct polymorphic function of the derived class will be called. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

388 388 Virtual Functions (cont) #include // Prog7.1 class ShapeBase { public: virtual void draw() { cout << "ShapeBase::draw() operation evoked" << endl; } virtual void rotate() { cout << "ShapeBase::rotate() operation evoked" << endl; } }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

389 389 Virtual Functions (cont) The base class shape_base is inherited by the two derived classes circle_derived and square_derived. The virtual functions draw() and rotate() will be overridden by function having identical names in the derived classes. Exercise Prog7.1 Sketch UML diagrams for Prog7.1. Compile and run the program, and examine its behavior. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

390 390 Virtual Functions (cont) #include // Prog7.2 class BaseTpu { public: virtual void display() { cout << "BaseTpu::display() operation evoked" << endl; } }; class ArincTx : public BaseTpu { //Inherit base class BaseTpu public: void display() { cout << "ArincTx::display() Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

391 391 Virtual Functions (cont) #include // Prog7.3 class BaseController { protected: double r, o, e; public: void perform() { action(); } virtual void action() { cout << "BaseController::action() operation evoked" << endl; cout << "Give reference input = "; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

392 392 Virtual Functions (cont) Exercise Prog7.2 & Prog 7.3 Sketch UML diagrams for Prog7.2 & Prog7.3 Compile and run the programs, and comment on the behavior of each program. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

393 393 Virtual Functions (cont) (Virtual functions without using pointers) #include // Prog7.4 class BaseController { protected: double r, o, e; public: void perform() { action(); } virtual void action() { cout << "BaseController::action() operation evoked" << endl; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

394 394 Virtual Functions (cont) Exercise Prog7.4 Sketch UML diagrams for Prog 7.4. Compile and run the program, and comment on its behavior. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

395 395 What are the Differences in Behavior Between Normal and Virtual Functions ? #include // Prog7.5 class Gyro { public: virtual void virtual_display_1() { cout << "Gyro::virtual_display_1() operation evoked" << endl; } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

396 396 Differences Between Normal and Virtual Functions (cont) Exercise Prog7.5 Sketch UML diagrams for Prog7.5. Compile and run the program and explain its behavior. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

397 397 Differences Between Normal and Virtual Functions (cont) Calls to virtual functions are resolved during run time -- late or dynamic binding. Calls to normal functions are resolved during compile time -- early or static binding. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

398 398 Are There Any Specialties of Virtual Functions ? It is illegal to declare a virtual function to be static. Virtual functions are operations tied to an object. On the other hand, a static function do not bind to any object; they are class operations, and accessible without instantiating of the class. A virtual function can be defined in a base class without any overriding function in the derived class. In such a case, the base class Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

399 399 Specialties of Virtual Functions (cont) definition will be used whenever the function is called. Because of above reason, it is illegal to declare a function prototype, in a base class, to be virtual; and then provide definition for the prototype in a derived class for overriding. A virtual function in the base class must be defined. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

400 400 Specialties of Virtual Functions (cont) However, a pure virtual function in a base class need not have any definition. But, if there is one the compiler will not complain. All functions in derived classes which override a virtual function in a base class are themselves virtual functions -- no explicit virtual declarations are required. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

401 401 Specialties of Virtual Functions (cont) In a series of derived classes a virtual function may be successively overridden. The last override will be used when the function is called using a pointer to the base class. It is illegal to declare a friend function to be virtual since it is not a member function; and so it cannot be overridden in a derived class. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

402 402 Specialties of Virtual Functions (cont) However, it is quite legal to declare a virtual function in one class to be a friend virtual function in another class, as long as no derivation is involved. It is illegal to declare a constructor to be virtual. This is because exact type of a class must be known before an object can be created or instantiated. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

403 403 Specialties of Virtual Functions (cont) Some destructor functions can be declared virtual. It is a must to do so, when new and delete operators are used with objects that are accessed through pointers or references to their base class. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

404 404 Specialties of Virtual Functions (cont) #include // Prog7.6 //Forward declaration for class Display used for reference class Display; class Gyro { public: virtual void display(Display&); }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

405 405 Specialties of Virtual Functions (cont) Exercise Prog7.6 Sketch UML diagrams for Prog7.6. Compile and run the program, and explain how it works. Remove friend void ElevationGyro::display(Display &obj); from class Display. Compile and run the program once again, and comment on the behavior. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

406 406 When is it Legal to Have Different Return Types in a Virtual Function ? In general, virtual functions must be identical in terms of their names, parameter lists and return types. Only in one special case the virtual functions are allowed to have different return types than the one in the base class. If the overridden virtual function Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

407 407 Legality of Different Return Types in a Virtual Function (cont) returns a pointer or a reference to a base class, and the overriding function is allowed to return a pointer or a reference to a class derived from this base class. However, the overriding function must be able access the derived class object being returned. This means that it must be: (1) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

408 408 Legality of Different Return Types in a Virtual Function (cont) the overriding function’s class or (2) the overriding function’s class must be declared a friend of that derived object class. The returned object is converted to the return type of the overridden function. Const-ness of the overridden return type must not be violated by the override. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

409 409 Legality of Different Return Types in a Virtual Function (cont) class A_base { public: void func_A_base(); …… }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

410 410 Legality of Different Return Types in a Virtual Function (cont) class B_derived { friend class D_derived; public: void func_B_derived(); …… }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

411 411 Legality of Different Return Types in a Virtual Function (cont) class C_base { public: virtual void vir_func1_C_base(); virtual C_base* vir_func2_C_base(); virtual C_base* vir_func3_C_base(); …… }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

412 412 Legality of Different Return Types in a Virtual Function (cont) class D_derived : public C_base { public: double vir_func1_C_base(); //Illegal B_derived* vir_func2_C_base() { //Alright …………. return &d; } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

413 413 Legality of Different Return Types in a Virtual Function (cont) D_derived* vir_func3_C_base() { …………. return this; } }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

414 414 Legality of Different Return Types in a Virtual Function (cont) Class D_derived tries to override three functions declared virtual in the base class C_base by changing their return types. First override to double vir_func1_C_base() fails because the return types are not compatible. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

415 415 Legality of Different Return Types in a Virtual Function (cont) The second override to B_derived* vir_func2_C_base() is legal because the return type address &d is of class D- derived, and this class is a friend of B_derived. The third and the final override is also Okay. This is because D_derived* vir_func3_C_base() returns pointer “this” Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

416 416 Legality of Different Return Types in a Virtual Function (cont) which is pointing an object of type class D_derived itself in which the overridden function resides. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

417 417 What is an Abstract Class ? An abstract class defines a concept or a generalized type. An abstract class cannot be used by itself. It can be only inherited as a base class by a derived class. An abstract class must have at least one pure virtual function. A pure virtual function imparts the abstract character to the base class or is the essence of Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

418 418 Abstract Class (cont) abstractness. An abstract class cannot be used as -- an argument type, -- a function return type, -- the type of an explicit conversion, or -- the type of an object. The following are illegal usage of an abstract class A_abstract. A_abstract a; //Instantiation illegal A_abstract func(); //Illegal return type Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

419 419 Abstract Class (cont) void func(A_abstract); //Illegal argument type ptr2 = (A_abstract*) ptr1; //Illegal expl conv A pointer or a reference may, however, be declared to an abstract class. class B_derived : A_abstract { …….. }; ….. B_derived* b = new B_derived; A_abstract* a = b; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

420 420 What is a Pure Virtual Function ? A pure virtual function is the essence of an abstract class. A pure virtual function has the following syntax: virtual type funct_name(args) = 0; It is usual for a pure virtual function to have no definition. It is merely a gateway to other concrete member functions defined in a derived class. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

421 421 Pure Virtual Function (cont) A pure virtual function is inherited as a pure virtual function. In a derived concrete class there must be a definition for the pure virtual function. In an abstract class a pure virtual function need not have a function definition. However, if this is to be called using the scope resolution operator :: then and then only that a function definition is required. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

422 422 Pure Virtual Function (cont) #include // Prog7.7 #include //ABSTRACT CLASS class InputEvent { char out_str[70]; public: InputEvent() { strcpy(out_str, "InputEvent::Base object type InputEvent is created.\n"); } //Pure virtual specifier. Note the 0 -- no definition for the function provided. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

423 423 Pure Virtual Function (cont) Exercise Prog7.7 Sketch UML diagrams for Prog7.7. Compile and run the program. Remove the comment symbol from the virtual display(), compile and rerun the program such that this virtual display() is executed. Comment on the behavior. In base class InputEvent delete the virtual specifier, and run the program to get displays from both base and derived classes. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

424 424 Pure Virtual Function (cont) Exercise Prog7.7 (cont) Repeat above using pointers. Next insert code in main() to show polymorphism. Comment out the concrete virtual function, and use the pure virtual function instead. Rerun the program, and comment on the behavior. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

425 425 How an Object of a Derived Class Constructed ? To begin with, constructors of all virtual base classes are invoked in the order they were declared. Next, all nonvirtual base class constructors are invoked in the order they were declared. The derived class constructor is executed last. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

426 426 How an Object of a Derived Class Destroyed ? To begin with, the derived class destructor is executed. Next, all nonvirtual base class destructors are invoked in the reverse order they were declared. Finally, destructors of all virtual base classes are invoked in the reverse order they were declared. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

427 427 How an Object of a Derived Class Constructed and Destroyed ? class A_base { public: A_base(); //Default constructor ………. ~A_base(); //Default destructor }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

428 428 Construction and Destruction of an Object of a Derived Class (cont) class B_derived : public A_base { public: B_derived(); //Default constructor ………. ~B_derived(); //Default destructor }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

429 429 Construction and Destruction of an Object of a Derived Class (cont) void main() { ………. public: // Create object b of type class B_derived B_derived b; ………. } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

430 430 Construction and Destruction of an Object of a Derived Class (cont) When an object b of type class B_derived is created the default constructor for the base class A_base is called first, and then the default constructor for the derived class B_derived. When the b object goes out of scope of of the main() the default destructors are called in the following sequence. B_derived() Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

431 431 Construction and Destruction of an Object of a Derived Class (cont) first, and then A_base(). Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

432 432 Virtual Destructor (cont) It is illegal to declare a constructor virtual. Constructor and destructor function cannot be inherited. Virtual destructors are required for objects created using the operator new, and then deleted using the operator delete. These operators returns pointers or references which are declared to be of the base class Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

433 433 Virtual Destructor (cont) type. class A_base { public: A_base(); //Default constructor ………. virtual ~A_base(); //Default destructor }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

434 434 Virtual Destructor (cont) class B_derived : public A_base { public: B_derived(); //Default constructor ………. ~B_derived(); //Default destructor }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

435 435 Virtual Destructor (cont) void main() { ………. public: // Create object of type class B_derived //with a pointer b to its base class A_base. A_base* b = new B_derived; ………. delete b; } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

436 436 Virtual Destructor (cont) b is now a pointer to A_base; therefore, only the destructor for A_base is invoked. The destructor for B_derived is left untouched. Declaring the destructor for A_base to be virtual ensures that the destructor in the derived class B_derived automatically overrides the destructor of the base class A_base. This ensures that all destructors are invoked one after another beginning with Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

437 437 Virtual Destructor (cont) that of the derived class, and then up the hierarchy chain. It is considered good programming practice to provide to any base class containing virtual functions, a virtual destructor function as well. This will ensure correct execution of destructor in any derived classes. It is also considered good programming practice to provide an empty virtual destructor even if the base class does Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

438 438 Virtual Destructor (cont) not need one, thus ensuring its safe usage. A derived class devoid of any overriding virtual function are not dynamically created, and then destroyed with a pointer to its base class. The corresponding base class, therefore, do not require a virtual destructor function. The constructor and destructor functions of a class may contain virtual functions. However, a call to any of the constructor or Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

439 439 Virtual Destructor (cont) destructor functions will result in the overriding function in the derived class to be ignored. The function called will be either in the constructor’s or destructor’s own class or in its base(s). This safeguards against any call to parts of the object not yet constructed. However, it must be emphasized that calling any other virtual function will result in the overriding function in the derived class to Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

440 440 Virtual Destructor (cont) be invoked. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

441 441 Virtual Destructor (cont) #include // Prog7.8 #include class MouseEvent { char out_str[70]; public: MouseEvent() { strcpy(out_str, "MouseEvent::Base object type MouseEvent is created.\n"); } virtual ~MouseEvent() { Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

442 442 Virtual Destructor (cont) Exercise Prog7.8 Sketch UML diagrams for Prog7.8. Compile and run the program. Remove the keyword virtual from the base class destructor. Compile and run the program once again, and comment on the behavior change. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

443 443 Close END OF CHAPTER 7 Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

444 444 Chapter 8 Class Templates Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

445 445 What is a Class Template ? A template is a common definition for a set of classes and functions. Templates are a major support for code reuse. Template classes are used for implementing container classes such as lists and queues. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

446 446 How Class Templates Used ? Templates are parameterized. Instances of a template are generated by supplying a set of arguments. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

447 447 UML Diagrams for Template and Instantiated Classes Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

448 448 Use of Class Templates (cont) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

449 449 Use of Class Templates (cont) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

450 450 Use of Class Templates (cont) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

451 451 Use of Class Templates (cont) template //Prog8.1 class ArincTxBuffer { public: ArincTxBuffer(int lower_index, int upper_index); // Copy constructor ArincTxBuffer(const ArincTxBuffer&); // Assignment operator = ArincTxBuffer& operator = (const ArincTxBuffer&); // Store value at index void insert(int index, const Type&); Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

452 452 Use of Class Templates (cont) Exercise Prog8.1 Compile and run program Prog8.1, and explain its behavior. Modify the destructor function to print out “Deleted buffer”. Remove the following from the main program and run the program again. theArincTxBuffer1.~ArincTxBuffer(); theArincTxBuffer2.~ArincTxBuffer(); theArincTxBuffer3.~ArincTxBuffer(); Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

453 453 Use of Class Templates (cont) The type of object stored in class ArincTxBuffer is parameterized as Type. Because of above an object of ArincTxBuffer class type can contain almost any type of object, (basic type or user defined type class objects). The only restriction is that the type must supports all the operations performed on it by the class ArincTxBuffer. The template declares the parameter using preceding keyword class. template // Type is the parameter type Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

454 454 Use of Class Templates (cont) Any valid C++ identifier is acceptable as a parameter name. It is legal to have more than one parameter. Instance of a template is first created by supplying actual Type of the parameter. An object of the template instance is then created, in the usual fashion, by calling a constructor and supplying it with constructor parameter values, if any. ArincTxBuffer theArincTxBuffer_Obj1 (1, 10) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

455 455 Use of Class Templates (cont) 1 and 10 are the lower and upper indices respectively of the standard constructor. FaultLocations theFault_Obj1; ……. // Codes to insert fault locations ArincTxBuffer theArincTxBuffer_Obj2 (10, 100) In above template ArincTxBuffer is used to create two different container objects, each containing different Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

456 456 Use of Class Templates (cont) objects. The first, contains basic type double; and the second contains objects instantiated from user defined class FaultLocations. Once an object is created from a template, it is used like any other object. A template with class parameters is polymorphic. An instance of a template is only compatible with the type of object for which it is defined. The following function will accept theArincTxBuffer_Obj1 but not theArincTxBuffer_Obj2 as an object. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

457 457 Use of Class Templates (cont) void ArincTxBuffer ::insert(int index, const double&); Member function of a template class is defined as follows for out-of-line implementation. template void ArincTxBuffer ::insert(int index, const Type& obj) { buffer[index - low] = obj; } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

458 458 Use of Class Templates (cont) Upon declaring an instance of template class ArincTxBuffer such as ArincTxBuffer correct version of the template class member function will be generated. void ArincTxBuffer ::insert(int index, const FaultLocations & obj) For inline implementation of member function we omit the template class name, and the scope resolution operator ::. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

459 459 Use of Class Templates (cont) template class ArincTxBuffer { public: ……….. void insert(int index, const Type& obj) { buffer[index - low] = obj; } ………….. }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

460 460 Use of Class Templates (cont) #include // Prog8.2 enum BOOL { FALSE, TRUE }; template class container { TYPE* elements; int number_of_elements_in_container; public: container( int size ); ~container(); Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

461 461 Use of Class Templates (cont) Exercise Prog8.2 Compile and run program Prog8.2, and explain its behavior. Modify the destructor function to print out “Deleted elements”, and run the program again. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

462 462 What is a Function Template ? A template function is generic. Compiler automatically makes use of template functions whenever appropriate. Thus, defining template functions forces the compiler to do all the hard work as and when required. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

463 463 How Function Templates Used ? template Type& max(Type& a, Type& b) { if (a > b) return a; else return b; } The above template is used by the compiler to automatically create an appropriate function whenever max with two arguments of identical type is called. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

464 464 Use of Function Templates (cont) double a, b; int c, d; max(a, b); max(c, d); max(a, c) ; // Illegal, arguments do not match template Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

465 465 What are Template Arguments ? Most common template arguments are type names. Constant expressions, character strings and function names can also be used as template arguments. Prog8.1 above is, once again, presented below but with the upper and lower bounds defined as template arguments. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

466 466 Template Arguments (cont) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

467 467 Template Arguments (cont) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

468 468 Template Arguments (cont) Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

469 469 Template Arguments (cont) //ArincTxBuffer template parameterized by type, and containing template arguments. //Prog8.3 template class ArincTxBuffer { public: // Store value at index void insert(int index, const Type&); Type fetch(int index) const; // Fetch value from index Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

470 470 Template Arguments (cont) Private attribute Type buffer is now statically allocated at compile time. Its size is calculated from template parameters. Template class ArincTxBuffer can be implemented without the need of dynamic memory allocation on the fly. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

471 471 Template Arguments (cont) Exercise Prog8.3 Compile and run program Prog8.3, and explain its behavior. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

472 472 Template Arguments (cont) Since the upper and lower bounds also become a part of template ArincTxBuffer instance’s type, some operations may be restricted. ArincTxBuffer theArincTxBuffer1; ArincTxBuffer theArincTxBuffer2; ArincTxBuffer theArincTxBuffer3; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

473 473 Template Arguments (cont) theArincTxBuffer1 = theArincTxBuffer3; // Okay theArincTxBuffer2 = theArincTxBuffer1; // Illegal, // mismatch of upper and lower bounds Function name may be used as a template non-type parameter. template class FaultManager { public: void use_it(); }; Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

474 474 Template Arguments (cont) template void FaultManager ::use_it() { func1() ; // call template argument } Here is how the above template is first instantiated for use with any given function, and then an object of the template instance created. Let any function be ---- void any_function () FaultManager obj; obj.use_it (); // calls any_func () Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

475 475 Template Arguments (cont) Array may be used as a template non-type parameter. template class FaultDisplay { public: display (); }; template void FaultDisplay ::display() { cout << “Fault is “ << buffer << endl; } Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

476 476 Template Arguments (cont) The above template is first instantiated, and then an object of the template instance is created as follows. const char fault[] = “Fuel pump Fl820 loosing pressure.”; FaultDisplay obj1; obj1.display; For some compilers arrays need to be defined as global variables before they can be used as template arguments. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

477 477 What are Drawbacks of Templates ? Drawbacks and disadvantages of templates are related only to their design and implementation. A compiler may be unable to detect directly errors in a template, but will do so only when an instance of a template has been generated and used. This may lead to considerable confusion, and bug removal can become arduous and time consuming. A template needs to be thoroughly tested with all possible combination of parameterized types. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

478 478 Drawbacks of Templates (cont) Syntax of related templates can be extremely complicated. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

479 479 What is the Recommended Approach to Template Design ? At the outset use non-parameterized prototype to model a specific instance of the template using ordinary class or function. Then, try out the class or function manually simulating all possible instances that the template is supposed to create. Subsequently, convert with caution, the above class or function to a fully operational template by gradual introduction of parameterized types, and testing. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

480 480 Template Design (cont) Finally, perform extensive testing of the template before releasing. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

481 481 Class List Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

482 482 Further Examples of Templates #ifndef Fault_h //Prog8.4 #define Fault_h 1 #include class Fault { char name[80]; public: Fault() {} Fault(char* xname) { strcpy(name, xname); } void display() { cout << name << endl; } }; #endif Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

483 483 Examples of Templates (cont) Exercise Prog8.4 Compile and run program Prog8.4, and explain its behavior. Sketch the Sequence and Collaboration diagrams. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

484 484 Class Diagram for StandardQueue Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

485 485 Further Examples of Templates #ifndef Fault_h //Prog8.5 #define Fault_h 1 #include class Fault { char name[80]; public: Fault() {} Fault(char* xname) { strcpy(name, xname); } void display() { cout << name << endl; } }; #endif Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

486 486 Examples of Templates (cont) Exercise Prog8.5 Compile and run program Prog8.5, and explain its behavior. Sketch the Sequence and Collaboration diagrams. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

487 487 Class Link Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

488 488 Examples of Templates (cont) #ifndef Link_h //Prog8.6 #define Link_h 1 #include "types.h" template class Link { public: //This constructor shall initialize the_object_reference //to object_ref. Link (Type *object_ref); Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

489 489 Class LinkedListIterator Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

490 490 Class Diagram for LinkedList Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

491 491 Class LinkedList Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

492 492 Examples of Templates (cont) Exercise Prog8.6 Develop a main program which uses LinkedList for data storage, along lines similar to those of Exercise 3.7. Write your program by suitably editing the void main() from Prog8.5. Sketch the Sequence and Collaboration diagrams. Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737

493 493 Close END OF CHAPTER 8 Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737


Download ppt "1 An Introduction to C++ Computer Language Using UML --BASICS-- Embedded Controller Designers For Copyright©1998 by Sayeed Nurul Ghani. All rights reserved."

Similar presentations


Ads by Google