An Introduction to C++
Computer Language Using UML
--BASICS-For
Embedded Controller
Designers
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
1
Introduction
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
2
Relevance
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
3
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, Az85737
4
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
5
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
6
Objectives
On completion of the course the participants
should be able to:
 Appreciate the principles of objectoriented 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
7
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
8
Course Structure
Module 1
Lab
Module 2
Lab
Module n
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
Lab
9
Overview of Programming
Techniques
• Unstructured Programming
Main Program
DATA
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
10
Overview of Programming
Techniques
• Procedural Programming
main program
procedure
Main Program
DATA
Executions of procedure
Procedure 1
Procedure 2
Procedure 3
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
11
Overview of Programming
Techniques
• Modular Programming
Main Program
GLOBALDATA
Module 1
Module 2
global data + local data
global data + local data
Procedure 1
Procedure 2
Procedure 3
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
12
Overview of Programming
Techniques
• Object Oriented Programming
Object 1
Object 2
data, operations
data, operations
Object 3
data, operations
Object 4
data ,operations
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
13
Text Books
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
14
What is Object-orientation ?
Object-oriented programming system (OOPS)
stands on three pillars:
(a) abstract
data typing - classes,
(c) polymorphism dynamic binding
(b) type derivation
- inheritance
•Definitions will be provided latter.
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
15
Chapter 1
Overview of a C++ Class
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
16
Simple Input and Output
#include <iostream.h>
// Prog 1.1
void main() {
const int i = 5;
int k;
for ( k=0; k < i; ++k) {
cout << "Numbers are: " << k << " " <<endl;
}
}
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
17
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 <iomanip.h> if setw(int w) is used.
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
18
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
19
Simple Input and Output (cont)
#include <iostream.h>
// 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
20
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
21
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
22
Why C++ class ? (cont)
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.
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
23
Why C++ class ? (cont)
• 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.
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
24
What is a C Structure? (cont)
#include <stdio.h>
#include <string.h>
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
25
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
26
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
27
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
28
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
29
C++ Structure (cont)
#include <iostream.h>
#include <string.h>
struct employee_record {
char surname[30];
char first_name[30];
char middle;
char ssn[12];
int hours;
employee_record();
// Prog1.3
//Structure definition
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
30
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
31
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
32
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
33
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
34
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
35
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
36
C++ Structure Accessibility
(cont)
Structure
surname[30];
first_name;
middle;
ssn[12];
hours;
employee_record();
show_it();
Public
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
37
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
38
Accessibility in a C++ class (cont)
Class
Operations
Attributes
employee_record()
show_it()
surname[30]
first_name[30]
middle
ssn[12]
Public
Private
• Protected will be discussed later when inheritance is introduced.
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
39
UML Diagram for a Class
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
40
Accessibility in a C++ class
(cont)
#include <iostream.h>
// 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
41
•
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
42
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
43
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
44
Accessibility in a C++ class
#include <iostream.h> (cont) // 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
45
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
46
UML Class Diagram
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
47
Sequence Diagram
gs : Guidance
Subsystem
: main
fcis : FlightCrew
InterfaceSubsystem
1: print_it()
Prog 1.6
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
48
Collaboration Diagram
gs : Guidance
Subsystem
1: print_it()
fcis : FlightCrew
InterfaceSubsystem
: main
Prog 1.6
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
49
Visibility in a C++ class (cont)
#include <iostream.h>
//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
50
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
51
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
52
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
53
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
54
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
55
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
56
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
57
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
58
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
59
Structure of a C++ Program
(cont)
void reset();
void display();
//Declaration of operation
//Declaration of operation };
• Content of the Apu.cpp file
#include <iostream.h>
#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
60
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
61
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
62
Structure of a C++ Program
(cont)
iostream.h
prog_b.cpp
prog_b.o
class_a.h
main.cpp
main.o
math.h
class_a.cpp
class_a.o
library
prog_b.exe
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
63
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
64
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
65
Structure of a C++ Program
(cont)
• Content of the Apu.cpp file //Prog 1.8
#include <iostream.h>
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, Az85737
66
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
67
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
68
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
69
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
70
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
71
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
72
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
73
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
74
Default Arguments (cont)
#include <iostream.h>
// 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
75
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
76
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
77
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
78
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
79
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
80
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
81
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
82
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
83
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
84
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
85
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
86
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
87
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
88
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
89
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
90
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
91
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
92
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
93
Friend Function (cont)
#include <iostream.h>
// 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
94
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
95
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
96
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
97
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
98
Friend Function (cont)
#include <iostream.h>
// 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
99
Friend Function (cont)
Exercise Prog1.11
Compile and run Prog1.11.
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
100
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
101
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
102
Syntax for Global Class
Definition (cont)
inline return_type
class_name::inline_operation_definition() {
}
return_type
out-ofline_friend_operation_definition() { }
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
103
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
104
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
105
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
106
A Constant Object (cont)
Member functions declared constant can be
used with non-constant objects; but nonconstant 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
107
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
108
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
109
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
110
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
111
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
112
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
113
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
114
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
115
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
116
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
117
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
118
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
119
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
120
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
121
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
122
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 preincremented: *(++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
123
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
124
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
125
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
126
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
127
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
128
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
129
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
130
Pointers v Arrays
int record[11];
0 1 2 3 4 5 6 7 8 9 10
//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
131
Pointers v Arrays
// Access via pointer:
*ptr_record = 70; 0 1 2 3 4 5 6 7 8 9 10
70
ptr_record
//Access as array:
ptr_record[2] = 5;
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
132
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
133
How Do Objects Communicate ?
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
134
Class Diagram
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
135
Sequence Diagram
shutdown :
Shutdown
apu : Apu
: Environment
1: Create object shutdown
2: display()
3: Create object apu(&shutdown)
4: set_loss_both_egt_sd(TRUE)
5: set_loss_both_egt_sd(x)
6: display()
7: display()
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
136
Collaboration Diagram
1: Create object shutdown
2: display()
shutdown :
Shutdown
: Environment
3: Create object apu(&shutdown)
4: set_loss_both_egt_sd(TRUE)
6: display()
5: set_loss_both_egt_sd(x)
7: display()
apu : Apu
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
137
How Does Two Objects
Communicate ?
#include <iostream.h>
// 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
138
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
139
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
140
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
141
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
142
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
143
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
144
Functions Calls Using Pointers
(cont)
#include <iostream.h>
//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
145
Functions Calls Using Pointers
(cont)
##include <iostream.h>
//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
146
Close
END OF CHAPTER 1
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
147
Chapter 2
Mapping the Real World in
Objects and Classes
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
148
What are Objects ?
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
149
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
150
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
151
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
152
What are Classes and Objects ?
Class - Human
Object_3 - John
Object_1 - Jim
Object_2 -Susan
Specific instance of a class is an object.
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
153
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
154
What is Abstraction ?
• Abstraction
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
155
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
156
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
157
Abstraction (cont)
For dealer record:
Stock Number
Object type -- Automobile
Manufactu Date of
Model
rer
manufacture
Color
Price
Column in the table represents a characteristic or attribute
of the object type
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
158
Abstraction (cont)
For Govt Record:
Object type -- Automobile
License Manu
Date of
Date of
Model Owner
number facturer
manufacture Registration
VIN
Column in the table represents a characteristic or attribute
of the object type
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
159
Abstraction (cont)
For Govt Record:
Owner Name
Object type -- Automobile_Owner
Address
Column in the table represents a characteristic or attribute
of the object type
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
160
Abstraction (cont)
For Garage Record:
Object type -- Automobile
License Manu
Date of
Model Owner
Mileage
number facturer
manufacture
VIN
Column in the table represents a characteristic or attribute
of the object type
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
161
Abstraction (cont)
For Garage Record:
Owner Name
Object type -- Automobile_Owner
Address
Account
balance
Column in the table represents a characteristic or attribute
of the object type
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
162
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
163
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
164
What is a Class ?
• A class is an abstraction of a set of realworld 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
165
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
166
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
167
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
168
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
169
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
170
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
171
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
172
Identification of Classes (cont)
class ElectricMotor
Model Height
ft
no
Breadth
ft
Length
ft
Power Voltage
HP
Volt
MK121
1
1
2
5
200
MK250
2
2
3
15
415
The Specification -- What it means to be model MK250.
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
173
Identification of Classes (cont)
• A specification class usually has a
complementary instance class.
class ElectricMotorUsage
Serial
no
Model
no
12345
MK121
54321
MK250
Present location
At milling station no 2.
At room 5 driving compressor no 3.
Instance class objects (instances) that meet the specification.
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
174
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
175
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
176
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
177
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
178
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
179
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
180
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
181
Attributes (cont)
• Notations
UartDeviceConfig
baud_ word_
loop_back receiver_ data_received
parity
rate
length
_enable enable
_threshold
….
Empty table
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
182
Attributes (cont)
UartDeviceConfig
baud_rate
word_length
parity
loop_back_enable
receiver_enable
data_received_threshhold
interrupt_on_tx_buffer_em
pty
overrun_count
Graphical form
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
183
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
184
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
185
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
186
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
187
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
188
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
189
Descriptive Attributes (cont)
The desired_state of
VNS4321 is OPEN.
The current_state of
VNS4321 is CLOSED.
NorthSectorValve
NorthSectorValve
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
190
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
191
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
192
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
193
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
194
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
195
Naming Attributes (cont)
NorthSectorValve
north_sector_valve_ID
desired_state
current_state
controller_# (R)
calibrate()
get_value()
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
196
Naming Attributes (cont)
NorthSectorValve whose
north_sector_valve_ID is VNS4321.
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
197
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
198
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
199
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
200
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
201
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
202
Referential Attributes (cont)
Account
CreditCard
withdrawal_l
imit
pin
balance
transaction()
balance
pin
pin (R)
account_ID
query()
credit($: x)
Customer
name
address
account
phone
_ID
password
account_ID (R)
debit($: y)
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
203
Close
END OF CHAPTER 2
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
204
Chapter 3
Constructors for C++ Objects
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
205
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
206
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
207
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
208
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
209
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
210
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
211
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
212
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
213
Storage Class Specifiers (cont)
#include<iostream.h>
//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
214
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
215
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
216
Storage Class Specifiers (cont)
#include <iostream.h>
// 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
217
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
218
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
219
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
220
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
221
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
222
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
223
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
224
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
225
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
226
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
227
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
228
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
229
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
230
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
231
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
232
Properties of Constructor
Functions (cont)
conversion.
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
233
Properties of Constructor
Functions (cont)
#include <iostream.h>
//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
234
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
235
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
236
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
237
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
238
Overloading Constructor (cont)
#include <iostream.h>
// 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
239
How to use Destructor ?
#include <iostream.h>
// Prog3.6
#include <string.h>
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
240
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
241
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
242
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
243
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
244
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
245
Usage of Destructor (cont)
#include <iostream.h>
//Prog3.8
#include <string.h>
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
246
Usage of Destructor (cont)
#include <iostream.h>
#include <string.h>
class Customer {
char* ptr;
public:
Customer(char* xname) {
ptr = new char[80];
strcpy(ptr, xname);
}
//Prog3.9
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
247
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
248
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
249
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
250
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-56529304-5.
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
251
Defining Local (auto) Class
Objects (cont)
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
252
Defining Local (auto) Class
Objects (cont)
: main
thedbllist :
dbllist
1: append("Arizona",8)
2: append("Washington",11)
3: append(*N. Dakota", 10)
4: append("Nevada",7)
5: gohead()
Repeat 6 and 7
till word is
NULL or false.
6: print(word)
7: gonext()
8: kill()
9: insert("Arizona",8)
10: insert("Washington",11)
11: insert("Nevada",7)
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
253
Defining Local (auto) Class
Objects (cont)
11: insert("Nevada",7)
12: gohead()
Repeat 13 and
14 till word is
NULL or false.
13: print(word)
14: gonext()
15: gotail()
Repeat 16 and
17 till word is
NULL or false.
16: print(word)
17: goprev()
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
254
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
255
Close
END OF CHAPTER 3
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
256
Chapter 4
Communication Between C++
Objects
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
257
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
258
Use of :: for Access (cont)
#include <iostream.h>
// 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
259
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
260
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
261
Use of :: for Access (cont)
#include <iostream.h>
// 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
262
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
263
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
264
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
265
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
266
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
267
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
268
C++ Scope Rules (cont)
main () {
class A a;
……
}
// Valid instantiation
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
269
C++ Scope Rules (cont)
#include <iostream.h>
// 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
270
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
271
What is the Difference Between
Reference Operator and Addressof 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
272
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
273
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
274
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
275
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
276
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
277
Advantages of Using Reference
(cont)
#include <iostream.h>
//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
278
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
279
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
280
Advantages of Using Reference
(cont)
correct print out.
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
281
Advantages of Using Reference
(cont)
#include <iostream.h>
//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
282
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
283
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
284
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
285
Use of Objects (cont)
#include <iostream.h>
// 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
286
Use of Objects (cont)
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
287
Communication Between Objects
theServoDrive :
ServoDrive
theFlightComputer
: FlightComputer
: main
1: message_to_FlightComputer(theFlightComputer)
2: integrity_test()
3: message_to_ServoDrive(theServoDrive)
4: display()
Sequence Diagram
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
288
Communication Between Objects
3: message_to_ServoDrive(theServoDrive)
theFlightComputer :
FlightComputer
: main
2: integrity_test()
1: message_to_FlightComputer(theFlightComputer)
4: display()
theServoDrive :
ServoDrive
Collaboration Diagram
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
289
Use of Objects (cont)
#include <iostream.h>
// 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
290
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
291
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
292
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
293
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
294
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
295
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
296
Using a Pointer (cont)
#include <iostream.h>
#include <string.h>
class employee {
char surname[30];
char first_name[30];
char middle;
char ssn[12];
int hours;
public:
// Prog 4.8
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
297
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
298
How are Pointers Used to Point
to Class Members ?
#include <iostream.h>
//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
299
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
300
How Bidirectional
Communication Implemented ?
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
301
Bidirectional Communication
(cont)
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
302
Bidirectional Communication
(cont)
optr : Operator
valve : Valve
Sequence Diagram
: main 1: set_theValve(&valve)
2: set_theOperator(&optr)
3: set_name("Brian Hicks")
4: set_name("Valve_1")
5: cout << get_name()
6: cout << get_name()
7: cout << get_valve_status()
8: close_valve()
9: set_valve_status(CLOSED)
10: cout << get_operator_name()
11: get_name()
12: cout << get_valve_status()
13: get_valve_status
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
303
Bidirectional Communication
(cont)
1: set_theValve(&valve)
3: set_name("Brian Hicks")
5: cout << get_name()
8: close_valve()
12: cout << get_valve_status()
optr :
Operator
: main
2: set_theOperator(&optr)
4: set_name("Valve_1")
6: cout << get_name()
7: cout << get_valve_status()
10: cout << get_operator_name()
11: get_name()
9: set_valve_status(CLOSED)
13: get_valve_status
valve :
Valve
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
304
Bidirectional Communication
#include <string.h> (cont)
//Prog4.10
#include <iostream.h>
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
305
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
306
Array of Pointers to Objects
(cont)
for (i = 0; i < 5; ++i) ghani[i]= new employee;
for (i = 0; i < 5; ++i) ghani[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
307
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
308
Array of Pointers to Objects
(cont)
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
309
Array of Pointers to Objects
(cont)
: Operator
: main
: Valve
1: create
2: create
3: set_name(string)
4: set_name(string)
5: set_valve_status(OPEN)
6: get_operator_name(theOperator[i])
7: get_name()
8: get_valve_name(theValve[i])
9: get_name()
10: get_valve_status(theValve[i])
11: get_valve_status()
12: close_valve(theValve[3])
13: set_valve_status(CLOSED)
14: get_name()
15: get_name()
16: get_valve_status()
17: delete
Copyright©1998 by Sayeed Nurul
18: delete
Ghani. All rights reserved. Tucson,
310
Array of Pointers to Objects
(cont)
2: create
4: set_name(string)
5: set_valve_status(OPEN)
6: get_operator_name(theOperator[i])
15: get_name()
16: get_valve_status()
18: delete
: Valve
7: get_name()
: main
1: create
3: set_name(string)
8: get_valve_name(theValve[i])
10: get_valve_status(theValve[i])
12: close_valve(theValve[3])
14: get_name()
17: delete
9: get_name()
11: get_valve_status()
13: set_valve_status(CLOSED)
: Operator
Collaboration Diagram
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
311
Array of Pointers to Objects
#include <iostream.h> (cont) // Prog4.11
#include <string.h>
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
312
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
313
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
314
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
315
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
316
Pointer to An Array of Objects
(cont)
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
317
Pointer to An Array (cont)
: Operator
: main
1: create
3: set_theValve(valve)
5: set_name(i)
10: get_valve_name(i)
12: get_valve_status(i)
14: get_name()
Sequence Diagram
: Valve
2: create
4: set_theOperator(optr)
6: set_name(i)
7: set_valve_status(OPEN)
8: get_operator_name(i)
9: get_name()
11: get_name()
13: get_valve_status()
15: get_name()
16: get_valve_status()
17: close_valve(2)
18: set_valve_status(CLOSED)
19: get_operator_name(3)
20: get_name()
21: get_valve_name(2)
22: get_name()
23: get_valve_status(2)
24: get_valve_status()
25: delete
Copyright©1998 by Sayeed 26:
Nurul
delete
Ghani. All rights reserved. Tucson,
318
Pointer to An Array of Objects
(cont)
11: get_name()
13: get_valve_status()
18: set_valve_status(CLOSED)
22: get_name()
24: get_valve_status()
: Valve
2: create
4: set_theOperator(optr)
6: set_name(i)
7: set_valve_status(OPEN)
8: get_operator_name(i)
15: get_name()
16: get_valve_status()
19: get_operator_name(3)
26: delete
9: get_name()
20: get_name()
: Operator
Collaboration
Diagram
: main
1: create
3: set_theValve(valve)
5: set_name(i)
10: get_valve_name(i)
12: get_valve_status(i)
14: get_name()
17: close_valve(2)
21: get_valve_name(2)
23: get_valve_status(2)
25: delete
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
319
Pointer to An Array of Objects
(cont)
#include <iostream.h>
#include <string.h>
enum { OPEN, CLOSED };
class Operator;
class Valve {
private:
char name[30];
bool valve_status;
static Operator *theOperator;
//Prog4.12
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
320
Close
END OF CHAPTER 4
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
321
Chapter 5
Derivation From a Single Base
Class
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
322
What is Type Derivation ?
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
323
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
324
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
325
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
326
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.
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
327
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
328
Class Composition (cont)
#include <iostream.h>
// 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
329
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
330
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
331
Class Composition (cont)
#include <iostream.h>
// 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
332
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
333
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
334
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
335
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
336
How to Inherit From a Single
Base Class ?
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
337
Object Communication
deriv_obj :
PositionSensor
: main
1: display()
2: display_b()
3: Sensor::display()
4: display() using pointer
to PositionSensor but
cast to Sensor class
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
338
Derivation from a Single Base
Class (cont)
#include <iostream.h>
// 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
339
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
340
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
341
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
342
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
343
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
344
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
345
Access Control Under Default
Derivation (cont)
functions.
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
346
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
347
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
348
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
349
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
350
Access Specifiers for Derived
Classes (cont)
#include <iostream.h>
// 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
351
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
352
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
353
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
354
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
355
Access Specifiers for Derived
Classes (cont)
#include <iostream.h>
//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
356
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
357
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
358
Resolving Ambiguity Using ::
(cont)
#include <iostream.h>
//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
359
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.
360
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
What is Pointer “this” ?
#include <iostream.h>
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
361
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
362
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
363
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
364
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
365
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
366
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
367
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
368
Behavior of Operator = Under
Derivation (cont)
#include <iostream.h>
//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
369
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
370
Behavior of Operator = Under
Derivation (cont)
#include <iostream.h>
// 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
371
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
372
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
373
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
374
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
375
Close
END OF CHAPTER 5
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
376
Chapter 6
Multiple Inheritance
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
377
Class Diagram
Vehicle
Land_Vehicle
Water_Vehicle
Air_Vehicle
Amphibious_Vehicle
Balloon
Space_Vehicle
Space_shuttle
Fixed_Wing_Vehicle
Rotary_Wing Vehicle
Tilt_Rotor_Vehicle
Multiple Inheritance
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
378
Close
END OF CHAPTER 6
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
379
Chapter 7
Polymorphism
&
Dynamic Binding
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
380
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
381
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
382
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
POLYMORPHISM
-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
383
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
384
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
385
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
386
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
387
Virtual Functions (cont)
#include <iostream.h>
// 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
388
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
389
Virtual Functions (cont)
#include <iostream.h>
// 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
390
Virtual Functions (cont)
#include <iostream.h>
// 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
391
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
392
Virtual Functions (cont)
(Virtual functions without using pointers)
#include <iostream.h>
// 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
393
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
394
What are the Differences in
Behavior Between Normal and
Virtual Functions ?
#include <iostream.h>
// 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
395
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
396
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
397
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
398
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
399
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
400
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
401
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
402
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
403
Specialties of Virtual Functions
(cont)
#include <iostream.h> //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
404
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
405
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
406
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
407
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
408
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
409
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
410
Legality of Different Return
Types in a Virtual Function
class C_base { (cont)
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
411
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
412
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
413
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
414
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 Dderived, 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
415
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
416
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
417
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
418
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
419
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
420
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
421
Pure Virtual Function (cont)
#include <iostream.h>
// Prog7.7
#include <string.h>
//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
422
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
423
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
424
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
425
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
426
How an Object of a Derived
Class Constructed and Destroyed
?
class A_base {
public:
A_base();
……….
~A_base();
};
//Default constructor
//Default destructor
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
427
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
428
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
429
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
430
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
431
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
432
Virtual Destructor (cont)
type.
class A_base {
public:
A_base();
……….
virtual ~A_base();
};
//Default constructor
//Default destructor
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
433
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
434
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
435
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
436
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
437
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
438
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
439
Virtual Destructor (cont)
be invoked.
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
440
Virtual Destructor (cont)
#include <iostream.h>
// Prog7.8
#include <string.h>
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
441
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
442
Close
END OF CHAPTER 7
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
443
Chapter 8
Class Templates
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
444
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
445
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
446
UML Diagrams for Template and
Instantiated Classes
TType, size
DoublyLinkedList
Explicit
parameterization
on the relationship
<<bind>> <integer,1000>
Implied refinement by
showing parameters
IntegerContainer
FaultLocationsContainer<FaultLocation,400>
Supported by Rose98
Supported by Rose98
Explicit parameterization
on the created class.
transaction,7000
DoublyLinkedTransactions
Not supported by Rose98
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
447
Use of Class Templates (cont)
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
448
Use of Class Templates (cont)
theArincTxBuffer1
: ArincTxBuffer1
: main
theArincTxBuffer2
: ArincTxBuffer2
theArincTxBuffer3
: ArincTxBuffer3
1: ArincTxBuffer<double> theArincTxBuffer1(3,10)
2: insert(4,4.4)
3: insert(5,5)
4: fetch(i)
5: ArincTxBuffer<double> theArincTxBuffer2(theArincTxBuffer1)
6: fetch(i)
7: ArincTxBuffer<double> theArincTxBuffer3(1,10)
8: fetch(i)
9: insert(7,7.7)
10: insert(8,8.8)
11: theArincTxBuffer3 = theArincTxBuffer1
12: fetch(i)
13: ~ArincTxBuffer()
14: ~ArincTxBuffer()
15: ~ArincTxBuffer()
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
449
Use of Class Templates (cont)
theArincTxBuffer1 :
ArincTxBuffer1
1: ArincTxBuffer<double> theArincTxBuffer1(3,10)
2: insert(4,4.4)
3: insert(5,5)
4: fetch(i)
9: insert(7,7.7)
10: insert(8,8.8)
13: ~ArincTxBuffer()
: main
7: ArincTxBuffer<double> theArincTxBuffer3(1,10)
8: fetch(i)
11: theArincTxBuffer3 = theArincTxBuffer1
12: fetch(i)
theArincTxBuffer3 : 15: ~ArincTxBuffer()
ArincTxBuffer3
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
5: ArincTxBuffer<double>
theArincTxBuffer2(the
6: fetch(i)
14: ~ArincTxBuffer()
theArincTxBuffer2 :
ArincTxBuffer2
450
Use of Class Templates (cont)
template< class Type >
//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
451
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
452
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 < class Type > // Type is the parameter type
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
453
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<double>
theArincTxBuffer_Obj1 (1, 10)
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
454
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<FaultLocations>
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
455
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
456
Use of Class Templates (cont)
void ArincTxBuffer<double>::insert(int index, const
double&);
• Member function of a template class is defined as
follows for out-of-line implementation.
template< class Type >
void ArincTxBuffer<Type>::insert(int index, const
Type& obj) {
buffer[index - low] = obj;
}
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
457
Use of Class Templates (cont)
Upon declaring an instance of template class
ArincTxBuffer such as
ArincTxBuffer<FaultLocations>
correct version of the template class member
function will be generated.
void ArincTxBuffer< FaultLocations >::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
458
Use of Class Templates (cont)
template< class Type >
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
459
Use of Class Templates (cont)
#include <iostream.h>
// Prog8.2
enum BOOL { FALSE, TRUE };
template<class TYPE>
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
460
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
461
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
462
How Function Templates Used ?
template<class Type>
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
463
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
464
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
465
Template Arguments (cont)
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
466
Template Arguments (cont)
theArincTxBuffer1
: ArincTxBuffer1
: main
1: ArincTx
Buffer<double,3,10>
theArincTxBuffer1
theArincTxBuffer2
: ArincTxBuffer2
theArincTxBuffer3
: ArincTxBuffer3
theArincTxBuffer4
: ArincTxBuffer4
Sequence Diagram
2: insert(4,4.4)
3: insert(5,5.5)
4: fetch[i]
5: ArincTxBuffer<double,3,10> theArinc
TxBuffer2(theArincTxBuffer1)
6: fetch[i]
7: ArincTxBuffer<double,1,10> the ArincTxBuffer3
8: fetch[i]
9: insert(7,7.7)
10: insert(8,8.8)
11: ArincTxBuffer<double,3,10> theArincTxBuffer4
12: theArincTxBuffer4 = theArincTxBuffer1
Copyright©1998
13: fetch[i]by Sayeed Nurul
Ghani. All rights reserved. Tucson,
467
Template Arguments (cont)
theArincTxBuffer1 :
ArincTxBuffer1
Collaboration Diagram
theArincTxBuffer2 :
ArincTxBuffer2
5: ArincTxBuffer<double,3,10> theArincTxBuffer2(the
ArincTxBuffer1)
1: ArincTxBuffer<double,3,10> theArincTxBuffer1
2: insert(4,4.4)
3: insert(5,5.5)
6: fetch[i]
4: fetch[i]
9: insert(7,7.7)
10: insert(8,8.8)
11: ArincTxBuffer<double,3,10> theArincTxBuffer4
12: theArincTxBuffer4 = theArincTxBuffer1
: main
13: fetch[i]
7: ArincTxBuffer<double,1,10> the ArincTxBuffer3
8: fetch[i]
theArincTxBuffer3 :
ArincTxBuffer3
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
theArincTxBuffer4 :
ArincTxBuffer4
468
Template Arguments (cont)
//ArincTxBuffer template parameterized by type, and
containing template arguments.
//Prog8.3
template< class Type, int LOW, int HIGH >
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
469
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
470
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
471
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<FaultLocations, 1, 10>
theArincTxBuffer1;
ArincTxBuffer< FaultLocations, 1, 100>
theArincTxBuffer2;
ArincTxBuffer<FaultLocations, 1, 10>
theArincTxBuffer3;
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
472
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< void (*func1) () >
class FaultManager {
public:
void use_it(); };
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
473
Template Arguments (cont)
template< void (*func1) () >
void FaultManager<func1>::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<any_function> obj;
obj.use_it ();
// calls any_func ()
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
474
Template Arguments (cont)
• Array may be used as a template non-type
parameter.
template< const char* buffer >
class FaultDisplay {
public:
display ();
};
template< const char* buffer >
void FaultDisplay<buffer>::display() {
cout << “Fault is “ << buffer << endl; }
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
475
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<fault> 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
476
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
477
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
478
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
479
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
480
Class List
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
481
Further Examples of Templates
#ifndef Fault_h
//Prog8.4
#define Fault_h 1
#include <string.h>
#include <iostream.h>
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
482
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
483
Class Diagram for
StandardQueue
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
484
Further Examples of Templates
#ifndef Fault_h
//Prog8.5
#define Fault_h 1
#include <string.h>
#include <iostream.h>
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
485
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
486
Class Link
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
487
Examples of Templates (cont)
#ifndef Link_h
//Prog8.6
#define Link_h 1
#include "types.h"
template <class Type>
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
488
Class LinkedListIterator
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
489
Class Diagram for LinkedList
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
490
Class LinkedList
Copyright©1998 by Sayeed Nurul
Ghani. All rights reserved. Tucson,
491
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
492
Close
END OF CHAPTER 8
Copyright©1998 by Sayeed Nurul Ghani. All rights reserved. Tucson, Arizona, Az-85737
493
Descargar

An Introduction to C++ Computer Language Using UML