Title: C %20Data%20Types%20and%20Data%20Abstractions
1CData Types and Data Abstractions
2C Data Types
- Namespaces
- Built-in data types
- Literal constants
- Variables
- Pointers
- References
- The C string Type
- The const Qualifier
3What is using namespace std
- include ltiostreamgt
- using namespace std
- void main ( )
- int start 5
- int end 19
- if (start lt end )
- cout ltlt A
- // end if
- cout ltlt B
- // end main
4Namespaces
- The problem When two variables (or functions) in
global scope have the same identifier (name), we
get a compile-time error. - To avoid such name collisions, programmers need
to use unique identifiers in their own code. - In C, if you use multiple third-party libraries
and there is a name collision, you have three
choices - Get the source code to the libraries and modify
and recompile it, - ask one of the library publishers to rename
their identifiers, or - decide not to use one of the libraries.
- Often, none of these options are available.
5Namespaces
- To tackle this problem, C introduced
namespaces. - All identifiers declared within a defined block
are associated with the blocks namespace
identifier. - All references to these identifiers from outside
the block must indicate the namespace identifier. - One example is the namespace std, in which
Standard C defines its librarys identifiers,
such as the cout stream object.
6Namespaces
- You can access objects in the namespace std in
the following way using the scope resolution
operator - include ltiostreamgt
- int main()
-
- stdcout ltlt Hello World!
- return 0
7Namespaces
- Or, you can use the using namespace statement to
omit the corresponding namespace references - include ltiostreamgt
- using namespace std
- int main()
-
- cout ltlt Hello World!
- return 0
8Namespaces
- This is how you define your own namespaces
- include ltiostreamgt
- namespace MyNames
-
- int value1 10
- int value2 20
- int ComputeSum()
-
- return (value1 value2)
-
-
- int main()
-
- stdcout ltlt MyNamesComputeSum() ltlt stdendl
9Namespaces
- If you use multiple using namespace statements,
you may get a compile-time error due to
ambiguity - include ltiostreamgt
- namespace MyNames
-
- int value1 10
- int value2 20
-
- namespace MyOtherNames
-
- int value1 30
- int value2 40
-
using namespace std using namespace
MyNames using namespace MyOtherNames int
main() value1 50
10Namespaces
- You can also define nested namespaces
- include ltiostreamgt
- namespace MyNames
-
- int value1 10
- int value2 20
- namespace MyInnerNames
-
- int value3 30
-
-
- int main()
-
- stdcout ltlt MyNamesvalue1 ltlt stdendl
- stdcout ltlt MyNamesMyInnerNamesvalue3 ltlt
stdendl
11Numeric Data Types
- Type char represents individual characters and
small integers (1 byte). - Types short, int, and long represent integer
values (half a machine word, 1 machine word, 1 or
more machine words) - Types float, double, and long double represent
floating point values (1 machine word, 2 machine
words, 3 or 4 machine words)
12Numeric Data Types
- Type char, short, int, and long are also called
integral types. - Integral types can be signed or unsigned.
- Example The value of an 8-bit unsigned char
ranges from 0 to 255, while the range for an
8-bit signed char is from 128 to 127.
13Literal Constants
- Literal constants are values that occur in a
program. - Example
- int main()
-
- int students 21
- double pi 3.1416
-
- Here, 21 is a literal constant of type int, and
3.1416 is a literal constant of type double.
14Literal Constants
- We can use prefixes to write literal integer
constants in decimal, octal, or hexadecimal
notation. - Examples Decimal (no prefix) 15
Octal (prefix 0 zero) 015
13 (decimal)
Hexadecimal (prefix 0x zero-x) 0x15
21 (decimal)
15Literal Constants
- By default, the C compiler assumes that all
literal integer constants are of type int and all
literal floating point constants are of type
double. - You can specify different types by appending a
letter to the literal integer constant. - Examples
- 2344U (unsigned)
- 1555L (long)
- 166UL (unsigned long)
- 3.1416F (float)
- 6.2831L (long double)
16Literal Constants
- Another built-in (or primitive) C data type is
the type bool. - Its only literals are true and false.
- Note that the type bool does not exist in C.
- In C, we represent the Boolean values true and
false by the integers 1 and 0.
17Literal Constants
- We use single quotation marks to write literal
character constants. - Examples x, 4, , (space)
- Nonprintable characters and some special
characters can be represented by escape
sequences. - Examples
- \n (newline), \a (bell), \t (tab)
- \\ (backslash), \ (single quote), \
(double quote)
18Literal Constants
- Generalized escape sequences are indicated by a
backslash followed by up to three digits. - The value of the digits in the sequence is
interpreted as the corresponding literal constant
in the ASCII character set. - Examples
- \7 (bell)
- \14 (newline)
- \65 (5)
19Literal Constants
- A character literal can be preceded by an L, for
example La - This is called a wide-character literal and has
type wchar_t. - Such wide-character literals support language
character sets like Chinese and Japanese, which
cannot be represented within the 256 character
ASCII set.
20Literal Constants
- A literal string constant is composed of zero or
more characters enclosed in double quotation
marks. - Examples
- (null string)
- x
- hello
- Hi,\nHow are you?\n
21Literal Constants
- A string literal can be written across multiple
lines. You can use a backslash as the last
character on a line to indicate that the string
continues on the next line. - Example
- This is an \
- excellent \
- multi-line string literal.
22Variables
- Variables provide us with named memory storage
that we can - write to,
- read from, and
- manipulate
- throughout the course of our program.
- Each variable has a specific type, which
determines - the size and layout of its associated memory,
- the range of values that can be stored, and
- the set of operations that can be applied to
it. - Variables are also referred to as objects.
23Variables
- There are two values associated with a variable
- Its data value, which is stored at some memory
address. It is also called the rvalue (read
value) of the variable. - Its address value, indicating the location in
memory where its data value is stored. This
value is also referred to as the variables
lvalue (location value).
24Pointers
- A pointer holds the memory address of another
object. - Through the pointer we can indirectly manipulate
the referenced object. - Pointers are useful for
- Creating linked data structures such as trees and
lists, - management of dynamically allocated objects, and
- as a function parameter type for passing large
objects such as arrays.
25Pointers
- Every pointer has an associated type.
- The type of a pointer tells the compiler how to
interpret the memory content at the referenced
location and how many bytes this interpretation
includes. - Examples of pointer definitions
- int pointer
- int pointer1, pointer2
- string myString
26Pointers
- The dereference operator () dereferences a
pointer variable so that we can manipulate the
memory content at the location specified by the
pointer. - The address-of operator () provides the memory
address (a pointer) of a given object.
27Pointers
- Example Correct or incorrect?
- int var1333, var2444, pvar1, pvar2
pvar1 var1
incorrect. int ? int
pvar2 var2
correct. int int
pvar1 var2
correct. int int
pvar2 pvar1 100
correct. int int
28Pointers
- Notice that in pointer definitions the symbol
indicates the pointer type and is not the
dereference operator. - Example
- int var
- int pvar1 var
- Incorrect! During initialization a pointer can
only be assigned an address - int var
- int pvar1 var
- Correct!
29References
- References (aliases) can be used as alternative
names for objects. - In most cases they are used as formal parameters
to a function. - A reference type is defined by following the type
specifier with the address-of operator. - Example
- int val1 333
- int refVal1 val1
30References
- A reference must be initialized.
- Once defined, a reference cannot be made to refer
to another object. - All operations on the reference are actually
applied to the object to which the reference
refers. - Example
- int val1 333
- int refVal1 val1
- val1
- refVal1 100
- cout ltlt Result ltlt refVal1
- Result 434
31Pass-by-value
sends a copy of the contents of the actual
parameter
SO, the actual parameter cannot be changed by
the function.
31
32Pass-by-reference
can change value of actual parameter
32
33The C string Type
- To use the C string type, you must include its
associated header file - include ltstringgt
- Different ways to initialize strings
- string myString(Hello folks!)
- string myOtherString(myString)
- string myFinalString // empty string
- The length of a string is returned by its size()
operation (without the terminating null
character) cout ltlt myString.size() - 12
34The C string Type
- We can use the empty() operation to find out
whether a string is empty - bool isStringEmpty myString.empty()
- Use the equality operator to check whether two
strings are equal - if (myString myOtherString)
- cout ltlt Wow, the strings are equal.
- Copy one string to another with the assignment
operator myFinalString myOtherString
35The C string Type
- Use the plus operator to concatenate strings
- string s1 Wow! , s2 Ouch!
- const char s3 Yuck!
- s2 s1 s3 s2
- cout ltlt s2
- Ouch! Wow! Yuck! Ouch!
36The const Qualifier
- The const type qualifier transforms an object
into a constant. Example const double pi
3.1416 - Constants allow you to store parameters in
well- defined places in your code - Constants have an associated type.
- Constants must be initialized.
- Constants cannot be modified after their
definition. - Constants replace the define technique in C.
37The const Qualifier
- Sometimes you may want to define for your object
a set of states or actions. - For example, you could define the following
states for the Student Counselor - observeStudent
- shoutAtStudent
- followStudent
- rechargeBattery
38The const Qualifier
- Using the const qualifier, you could define the
following constants - const int observeStudent 1
- const int shoutAtStudent 2
- const int followStudent 3
- const int rechargeBattery 4
- A function SetRobotState could then be defined as
follows - bool SetRobotState(int newState)
-
-
- int currentState newState
- return executionSuccessful
39Enumeration Types
- However, mapping states onto integers has certain
disadvantages - You cannot restrain the range of values that
are passed to SetRobotState. - There is no useful typing if you define
individual sets of states for multiple
objects, each object could formally be set
to any of these states, not only its
individual ones. - This problem can be solved with enumeration types.
40Enumeration Types
- Enumeration types can be defined as follows
- enum robotState observeStudent 1,
shoutAtStudent, -
followStudent, -
rechargeBattery - This way we defined a new type robotState that
can only assume four different values. - These values still correspond to integers. For
example, -
- cout ltlt followStudent
- gives you the output 3.
41Enumeration Types
- We are now able to restrain the values that are
passed to SetRobotState to the four legal ones - bool SetRobotState(robotState newState)
-
-
- robotState currentState newState
- return executionSuccessful
-
- Any attempt to call SetRobotState with an integer
value or a value of a different enumeration type
will cause an error at compile time.
42C Data Types
structured
simple
array struct union class
integral enum
char short int long bool
43Structured Data Types
44C Data Types
structured
simple
Skipping for now
array struct union class
integral enum
char short int long bool
45Structured Data Type
- A structured data type is a type in which each
value is a collection of component items. - The entire collection has a single name each
component can be accessed individually
46C Structured Type
- Often we have related information of various
types that wed like to store together for
convenient access under the same identifier, for
example . . .
47thisAnimal
.id 2037581 .name
giant panda .genus
Ailuropoda .species melanoluka .count
ry China .age
18 .weight 234.6 .health
Good
48anotherAnimal
.id 5281003 .name
llama .genus Lama .species
peruana .country Peru .age
7 .weight 278.5 .health
Excellent
49struct AnimalType
- enum HealthType Poor, Fair, Good,
Excellent - struct AnimalType // declares a struct data
type - // does not allocate memory
- long id
- string name
- string genus
- string species
struct members - string country
- int age
- float weight
- HealthType health
-
- AnimalType thisAnimal // declare variables
of AnimalType - AnimalType anotherAnimal
49
50struct type Declaration
- SYNTAX
-
- struct TypeName
-
- MemberList
-
- MemberList SYNTAX
- DataType MemberName
- DataType MemberName
- .
- .
- .
51struct type Declaration
- The struct declaration names a type and names the
members of the struct. - It does not allocate memory for any variables of
that type! - You still need to declare your struct variables.
52struct type declarations
- If the struct type declaration precedes all
functions it will be visible throughout the rest
of the file. If it is placed within a function,
only that function can use it. - It is common to place struct type declarations
with TypeNames in a (.h) header file and include
that file. - It is possible for members of different struct
types to have the same identifiers. Also a
non-struct variable may have the same identifier
as a structure member.
53Accessing struct Members
- Dot ( period ) is the member selection operator.
- After the struct type declaration, the various
members can be used in your program only when
they are preceded by a struct variable name and a
dot. - EXAMPLES
- thisAnimal.weight
- anotherAnimal.country
54Valid operations on a struct member depend only
on its type
- thisAnimal.age 18
- thisAnimal.id 2037581
- cin gtgt thisAnimal.weight
- getline ( cin, thisAnimal.species )
- thisAnimal.name giant panda
- thisAnimal.genus 0 toupper
(thisAnimal.genus 0 ) - thisAnimal.age
55Aggregate Operation
- An Aggregate operation is an operation on a data
structure as a whole, as opposed to an operation
on an individual component of the data structure.
56Aggregate struct Operations
- I/O, arithmetic, and comparisons of entire
struct variables are NOT ALLOWED! - Operations valid on an entire struct type
variable - assignment to another struct variable of same
type, - pass to a function as argument (by value or
by reference), - return as value of a function
57Examples of aggregate struct operations
- anotherAnimal thisAnimal // assignment
- WriteOut(thisAnimal) // value parameter
- ChangeWeightAndAge(thisAnimal) // reference
parameter - thisAnimal GetAnimalData( ) // return value
of function
58- void WriteOut( / in / AnimalType
thisAnimal) - // Prints out values of all members of thisAnimal
- // Precondition all members of thisAnimal
are assigned - // Postcondition all members have been
written out -
- cout ltlt ID ltlt thisAnimal.id ltlt
thisAnimal.name ltlt endl - cout ltlt thisAnimal.genus ltlt
thisAnimal.species ltlt endl - cout ltlt thisAnimal.country ltlt endl
- cout ltlt thisAnimal.age ltlt years ltlt
endl - cout ltlt thisAnimal.weight ltlt lbs. ltlt
endl - cout ltlt General health
58
59Passing a struct Type by Reference
- void ChangeAge ( / inout / AnimalType
thisAnimal ) - // Adds 1 to age
- // Precondition thisAnimal.age is assigned
- // Postcondition thisAnimal.age
thisAnimal.age_at_entry 1 -
-
- thisAnimal.age
-
60- AnimalType GetAnimalData ( void )
- // Obtains all information about an animal from
keyboard - // Postcondition
- // Function value AnimalType members entered
at kbd -
- AnimalType thisAnimal
- char response
- do // have user enter all members until
they are correct - .
- .
- .
- while (response ! Y )
- return thisAnimal
-
60
61Hierarchical Structures
- The type of a struct member can be another struct
type. This is called nested or hierarchical
structures. - Hierarchical structures are very useful when
there is much detailed information in each
record. - FOR EXAMPLE . . .
62struct MachineRec
- Information about each machine in a shop
contains - an idNumber,
- a written description,
- the purchase date,
- the cost,
- and a history (including failure rate, number
of days down, and date of last service).
63- struct DateType
- int month // Assume 1 . . 12
- int day // Assume 1 . . 31
- int year // Assume 1900 . . 2050
-
- struct StatisticsType
- float failRate
- DateType lastServiced // DateType is
a struct type - int downDays
-
- struct MachineRec
- int idNumber
- string description
- StatisticsType history //
StatisticsType is a struct type - DateType purchaseDate
- float cost
-
63
64struct type variable machine
5719 DRILLING
3 21 1995 8000.0
.02 1 25 1999 4
.month .day .year
.month .day .year
.failrate .lastServiced .downdays
.idNumber .description . history
.purchaseDate .cost
machine.history.lastServiced.year has value 1999
65C Data Types
structured
simple
array struct union class
integral enum
char short int long bool
66Unions in C
- Definition
- A union is a struct that holds only one of its
members at a time during program execution. - For Example
- union WeightType
-
- long wtInOunces
- int wtInPounds only one at a time
- float wtInTons
-
67Using Unions
- union WeightType // declares a union type
-
- long wtInOunces
- int wtInPounds
- float wtInTons
-
- WeightType weight // declares a union
variable - weight.wtInTons 4.83
- // Weight in tons is no longer needed. Reuse the
memory space. - weight.wtInPounds 35
68Abstraction
- Abstraction is the separation of the essential
qualities of an object from the details of how it
works or is composed - It focuses on what, not how
- It is necessary for managing large, complex
software projects
69Control Abstraction
- Separates the logical properties of an action
from its implementation - .
- .
- .
- Search (list, item, length, where, found)
- .
- .
- .
- The function call depends on the functions
specification (description), not its
implementation (algorithm)
70Data Abstraction
- Separates the logical properties of a data type
from its implementation
LOGICAL PROPERTIES IMPLEMENTATION
What are the possible values? How can this be
done in C? What operations will be
needed? How can data types be used?
71Data Type
set of values (domain)
allowable operations on those values
For example, data type int has
operations , -, , /, , gtgt, ltlt
domain -32768 . . . 32767
72Abstract Data Type (ADT)
- Is a programmer-defined type with a set of
- values and allowable operations for the type.
- Some ways to define a new C type are
- using typedef
- using struct
- using class
73Using typedef
- typedef int Boolean
- typedef char String20 21
- String20 message // variable declarations
- Boolean seniorCitizen
74Using struct
- typedef char String20 21
- struct EmployeeType // declares a struct
data type - long idNumber
- String20 name data
members - int hoursWorked
- int numDependents
- float hourlyWage
-
- EmployeeType mySelf // declares variable
75mySelf
76Abstract Data Type (ADT)
- An ADT is a data type whose properties
(domain and operations) are specified (what)
independently of any particular implementation
(how) - For example . . .
77ADT Specification Example
- TYPE
- TimeType
- DOMAIN
- Each TimeType value is a time in hours, minutes,
and seconds. - OPERATIONS
- Set the time
- Print the time
- Increment by one second
- Compare 2 times for equality
- Determine if one time is less than another
78Another ADT Specification
- TYPE
- ComplexNumberType
- DOMAIN
- Each value is an ordered pair of real numbers
(a, b) representing a bi. - OPERATIONS
- Initialize the complex number
- Write the complex number
- Add
- Subtract
- Multiply
- Divide
- Determine the absolute value of a complex number
79ADT Implementation means
- Choosing a specific data representation for
the abstract data using data types that already
exist (built-in or programmer-defined) - Writing functions for each allowable
operation
80Information Hiding
- Class implementation details are hidden from the
clients view. This is called information
hiding. - Public functions of a class provide the interface
between the client code and the class objects.
client code
abstraction barrier
specification
implementation
81Benefits of information hiding
- Data and details can be concealed from the client
of the abstraction. - Code can be changed without affecting the client
because the specification and interface are
unchanged.
82Several Possible Representations of TimeType
- 3 int variables
- 3 strings
- 3-element int array
- Actual choice of representation depends on
time, space, and algorithms needed to implement
operations
10 45 27
83Some Possible Representationsof ComplexNumberType
- struct with 2 float members
- 2-element float array
-16.2 5.8 .real .imag
-16.2 5.8
84C Data Types
structured
simple
array struct union class
integral enum
char short int long bool
85class TimeType Specification
- // Specification File ( timetype.h )
- class TimeType // declares a class data type
- // does not allocate memory
- public // 5 public function members
- void Set ( int hours , int mins , int
secs ) - void Increment ( )
- void Write ( ) const
- bool Equal ( TimeType otherTime )
const - bool LessThan ( TimeType otherTime )
const - private // 3 private data members
- int hrs
- int mins
- int secs
86Use of C data Type class
- Facilitates re-use of C code for an ADT
- Software that uses the class is called a client
- Variables of the class type are called class
objects or class instances - Client code uses public member functions to
handle its class objects
87Using class
- A class is a programmer-defined type whose
components (called class members) can be
variables or functions. - Class members are private by default. Compiler
does not permit client code to access private
class members. - Class members declared public form the interface
between the client and the class. - In most classes, the private members contain
data, and the public members are functions to
manipulate that data.
88Member functions categorized by task
- CONSTRUCTOR -- a member function that actually
creates a new instance and initialized some or
all of its data members - ACCESS FUNCTION or OBSERVER -- a member function
that can inspect (use but not modify) the data
members of a class without changing their values.
Such a function is declared with const following
the parameter list in both the specification and
the implementation files.
89Client Code Using TimeType
- include timetype.h // includes
specification of the class - using namespace std
- int main ( )
-
- TimeType currentTime // declares 2
objects of TimeType - TimeType endTime
- bool done false
- currentTime.Set ( 5, 30, 0 )
- endTime.Set ( 18, 30, 0 )
- while ( ! done )
- . . .
- currentTime.Increment ( )
- if ( currentTime.Equal ( endTime ) )
- done true
-
-
89
90class type Declaration
- The class declaration creates a data type and
names the members of the class. - It does not allocate memory for any variables of
that type! - Client code still needs to declare class
variables.
91C Data Type class represents an ADT
- 2 kinds of class members data members and
function members - Class members are private by default
- Data members are generally private
- Function members are generally declared public
- Private class members can be accessed only by the
class member functions (and friend functions),
not by client code.
92Aggregate class Operations
- Built-in operations valid on class objects are
- Member selection using dot ( . ) operator ,
- Assignment to another class variable using (
), -
- Pass to a function as argument
- (by value or by reference),
- Return as value of a function
- Other operations can be defined as class member
functions
932 separate files Generally Used for class Type
- // Specification File (
timetype .h ) - // Specifies the data and function members.
- class TimeType
-
- public
- . . .
- private
- . . .
-
- // Implementation File ( timetype.cpp
) - // Implements the TimeType member functions.
-
- . . .
94Implementation File for TimeType
- // Implementation File (
timetype.cpp ) - // Implements the TimeType member functions.
- include timetype.h // also must appear
in client code - include ltiostreamgt
- . . .
- bool TimeType Equal ( / in / TimeType
otherTime ) const - // Postcondition
- // Function value true, if this time
equals otherTime - //
false , otherwise -
- return ( (hrs otherTime.hrs) (mins
otherTime.mins) - (secs otherTime.secs) )
-
- . . .
95Member selection operator .
- When a client uses a public member function,
the function call requires a dot preceded by the
name of the object. You can think of the
function call as being sent to this object. - ofstream outFile
- outFile.open (a\\my.out)
- .
- .
- .
- outFile.close( )
class type
variable, object, instance
96Familiar Class Instances and Function Members
- The member selection operator ( . ) selects
either data members or function members - Header files iostream and fstream declare the
istream, ostream,and ifstream, ofstream I/O
classes - Both cin and cout are class objects and get and
ignore are function members - cin.get (someChar)
- cin.ignore (100, \n)
- The statements below, declare myInfile as an
instance of class ifstream and invoke function
member open - ifstream myInfile
- myInfile.open ( A\\mydata.dat )
97Scope Resolution Operator ( )
- C programs typically use several class types
- Different classes can have member functions with
the same identifier, like Write( ) - Member selection operator is used to determine
the class whose member function Write( ) is
invoked - currentTime .Write( ) // class TimeType
- numberZ .Write( ) // class ComplexNumberType
- In the implementation file, the scope resolution
operator is used in the heading before the
function members name to specify its class - void TimeType Write ( ) const
- . . .
-
98 TimeType Class Instance Diagrams
currentTime endTime
Set
Set
Private data hrs mins secs
Private data hrs mins secs
Increment
Increment
18 30 0
17 58 2
Write
Write
LessThan
LessThan
Equal
Equal
99Use of const with Member Functions
- When a member function does not modify the
private data members, use const in both the
function prototype (in specification file) and
the heading of the function definition (in
implementation file)
100Example Using const with a Member Function
- void TimeType Write ( ) const
- // Postcondition Time has been output
in form HHMMSS - if ( hrs lt 10 )
- cout ltlt 0
- cout ltlt hrs ltlt
- if ( mins lt 10 )
- cout ltlt 0
- cout ltlt mins ltlt
- if ( secs lt 10 )
- cout ltlt 0
- cout ltlt secs
-
100
101Class Constructors
- A class constructor is a member function whose
purpose is to initialize the private data members
of a class object - The name of a constructor is always the name of
the class, and there is no return type for the
constructor - A class may have several constructors with
different parameter lists. A constructor with no
parameters is the default constructor - A constructor is implicitly invoked when a class
object is declared--if there are parameters,
their values are listed in parentheses in the
declaration
102Specification of TimeType Class Constructors
- class TimeType // timetype.h
-
- public // 7 function members
- void Set ( int hours , int minutes ,
int seconds ) - void Increment ( )
- void Write ( ) const
- bool Equal ( TimeType otherTime )
const - bool LessThan ( TimeType otherTime )
const - TimeType ( int initHrs , int initMins ,
int initSecs ) // constructor - TimeType ( ) // default constructor
- private // 3 data members
- int hrs
- int mins
- int secs
-
102
103Implementation of TimeType Default Constructor
- TimeType TimeType ( )
- // Default Constructor
- // Postcondition
- // hrs 0 mins 0 secs 0
-
- hrs 0
- mins 0
- secs 0
104Implementation of Another TimeType Class
Constructor
- TimeType TimeType ( / in / int initHrs,
- / in / int initMins,
- / in / int initSecs )
- // Constructor
- // Precondition 0 lt initHrs lt 23 0
lt initMins lt 59 - // 0 lt initSecs lt 59
- // Postcondition
- // hrs initHrs mins initMins secs
initSecs -
- hrs initHrs
- mins initMins
- secs initSecs
104
105Automatic invocation of constructors occurs
- TimeType departureTime // default
constructor invoked - TimeType movieTime (19, 30, 0 ) //
parameterized constructor - departureTime movieTime
Set
Set
Private data hrs mins secs
Private data hrs mins secs
Increment
Increment
0 0 0
19 30 0
Write
Write
LessThan
LessThan
Equal
Equal
106Separate Compilation and Linking of Files
specification file
implementation file
main program
include timetype.h
Compiler
Compiler
Linker
107Avoiding Multiple Inclusion of Header Files
- Often several program files use the same header
file containing typedef statements, constants, or
class type declarations--but, it is a
compile-time error to define the same identifier
twice - This preprocessor directive syntax is used to
avoid the compilation error that would otherwise
occur from multiple uses of include for the same
header file - ifndef Preprocessor_Identifier
- define Preprocessor_Identifier
- .
- .
- .
- endif
108Example Using Preprocessor Directive ifndef
- // timetype .h FOR COMPILATION THE CLASS
DECLARATION IN - // Specification File FILE timetype.h WILL BE
INCLUDED ONLY ONCE - ifndef TIME_H
- define TIME_H // timetype .cpp //
client.cpp - // Implementation File //
Appointment program - class TimeType
- include timetype.h include
timetype.h - public
- . . . . . . int main ( void
) -
- private . . .
- . . .
-
- endif
109The End
- Next Lecture
- More about classes.
- How to create and use them.