C Data Types and Data Abstractions 1 C
C++ Data Types and Data Abstractions 1
C++ Data Types • • Namespaces Built-in data types Literal constants Variables Pointers References The C++ string Type The const Qualifier 2
What is “using namespace std; ” #include <iostream> using namespace std; void main ( ) { int start = 5; int end = 19; if (start < end ) { cout << “A”; } // end if cout << “B”; } // end main 3
Namespaces The problem: When two variables (or functions) in global scope have the same identifier (name), we get a compiletime 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. 4
Namespaces To tackle this problem, C++ introduced namespaces. All identifiers declared within a defined block are associated with the block’s 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 library’s identifiers, such as the cout stream object. 5
Namespaces You can access objects in the namespace std in the following way using the scope resolution operator “: : ” #include <iostream> int main() { std: : cout << “Hello World!”; return 0; } 6
Namespaces Or, you can use the using namespace statement to omit the corresponding namespace references: #include <iostream> using namespace std; int main() { cout << “Hello World!”; return 0; } 7
Namespaces This is how you define your own namespaces: #include <iostream> namespace My. Names { int value 1 = 10; int value 2 = 20; int Compute. Sum() { return (value 1 + value 2); } } int main() { std: : cout << My. Names: : Compute. Sum() << std: : endl; } 8
Namespaces If you use multiple using namespace statements, you may get a compile-time error due to ambiguity: #include <iostream> namespace My. Names { int value 1 = 10; int value 2 = 20; } namespace My. Other. Names { int value 1 = 30; int value 2 = 40; } using namespace std; using namespace My. Names; using namespace My. Other. Names; int main() { value 1 = 50; } 9
Namespaces You can also define nested namespaces: #include <iostream> namespace My. Names { int value 1 = 10; int value 2 = 20; namespace My. Inner. Names { int value 3 = 30; } } int main() { std: : cout << My. Names: : value 1 << std: : endl; std: : cout << My. Names: : My. Inner. Names: : value 3 << std: : endl; } 10
Numeric 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 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) 11
Numeric 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. 12
Literal 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. 13
Literal 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 0 x [zero-x]): 0 x 15 = 21 (decimal) 14
Literal 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: 2344 U (unsigned) 1555 L (long) 166 UL (unsigned long) 3. 1416 F (float) 6. 2831 L (long double) 15
Literal 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. 16
Literal 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) 17
Literal 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’) 18
Literal Constants A character literal can be preceded by an L, for example: L’a’ 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. 19
Literal Constants A literal string constant is composed of zero or more characters enclosed in double quotation marks. Examples: “” (null string) “x” “hello” “Hi, n. How are you? n” 20
Literal 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. ” 21
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. 22
Variables There are two values associated with a variable: 1. Its data value, which is stored at some memory address. It is also called the rvalue (read value) of the variable. 2. Its address value, indicating the location in memory where its data value is stored. This value is also referred to as the variable’s lvalue (location value). 23
Pointers • 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. 24
Pointers • 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 *pointer 1, *pointer 2; string *my. String; 25
Pointers 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. 26
Pointers Example: Correct or incorrect? int var 1=333, var 2=444, *pvar 1, *pvar 2; pvar 1 = var 1; incorrect. *int pvar 2 = &var 2; correct. *int = *int *pvar 1 = var 2; correct. int = int *pvar 2 = *pvar 1 + 100; correct. int = int 27
Pointers Notice that in pointer definitions the ‘*’ symbol indicates the pointer type and is not the dereference operator. Example: int var; int *pvar 1 = var; Incorrect! During initialization a pointer can only be assigned an address: int var; int *pvar 1 = &var; Correct! 28
References • 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 val 1 = 333; int &ref. Val 1 = val 1; 29
References • 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 val 1 = 333; int &ref. Val 1 = val 1; val 1++; ref. Val 1 += 100; cout << “Result: ” << ref. Val 1; Result: 434 30
Pass-by-value sends a copy of the contents of the actual parameter CALLING BLOCK FUNCTION CALLED SO, the actual parameter cannot be changed by the function. 31
Pass-by-reference sends the location (memory address) of the actual parameter CALLING BLOCK FUNCTION CALLED can change value of actual parameter 32
The C++ string Type To use the C++ string type, you must include its associated header file: #include <string> Different ways to initialize strings: string my. String(“Hello folks!”); string my. Other. String(my. String); string my. Final. String; // empty string The length of a string is returned by its size() operation (without the terminating null character): cout << my. String. size(); = 12 33
The C++ string Type We can use the empty() operation to find out whether a string is empty: bool is. String. Empty = my. String. empty(); Use the equality operator to check whether two strings are equal: if (my. String == my. Other. String) cout << “Wow, the strings are equal. ”; Copy one string to another with the assignment operator: my. Final. String = my. Other. String; 34
The C++ string Type Use the plus operator to concatenate strings: string s 1 = “Wow! ”, s 2 = “Ouch! ”; const char *s 3 = “Yuck! ” s 2 += s 1 + s 3 + s 2; cout << s 2; = Ouch! Wow! Yuck! Ouch! 35
The 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. 36
The 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: • • observe. Student shout. At. Student follow. Student recharge. Battery 37
The const Qualifier Using the const qualifier, you could define the following constants: const int observe. Student = 1; const int shout. At. Student = 2; const int follow. Student = 3; const int recharge. Battery = 4; A function Set. Robot. State could then be defined as follows: bool Set. Robot. State(int new. State) { … int current. State = new. State; return execution. Successful; } 38
Enumeration Types However, mapping states onto integers has certain disadvantages: • You cannot restrain the range of values that are passed to Set. Robot. State. • 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. 39
Enumeration Types Enumeration types can be defined as follows: enum robot. State { observe. Student = 1, shout. At. Student, follow. Student, recharge. Battery }; This way we defined a new type robot. State that can only assume four different values. These values still correspond to integers. For example, cout << follow. Student; gives you the output ‘ 3’. 40
Enumeration Types We are now able to restrain the values that are passed to Set. Robot. State to the four legal ones: bool Set. Robot. State(robot. State new. State) { … robot. State current. State = new. State; return execution. Successful; } Any attempt to call Set. Robot. State with an integer value or a value of a different enumeration type will cause an error at compile time. 41
C++ Data Types simple integral enum structured floating array struct union class char short int long bool float double long double address pointer reference 42
Structured Data Types Chapter 11 43
C++ Data Types simple structured Skipping for now… integral enum floating array struct union class char short int long bool float double long double address pointer reference 44
Structured 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 45
C++ Structured Type Often we have related information of various types that we’d like to store together for convenient access under the same identifier, for example. . . 46
this. Animal . id 2037581 . name “giant panda” . genus “Ailuropoda” . species “melanoluka” . country “China” . age 18 . weight 234. 6 . health Good 47
another. Animal . id 5281003 . name “llama” . genus “Lama” . species “peruana” . country “Peru” . age 7 . weight 278. 5 . health Excellent 48
struct Animal. Type enum Health. Type { Poor, Fair, Good, Excellent } ; struct Animal. Type { long id ; string name ; string genus ; string species ; string country ; int age ; float weight ; Health. Type health ; }; Animal. Type // declares a struct data type // does not allocate memory struct members this. Animal ; // declare variables of Animal. Type another. Animal ; 49 49
struct type Declaration SYNTAX struct Type. Name { Member. List }; Member. List SYNTAX Data. Type Member. Name ; . . . 50
struct 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. 51
struct 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 Type. Names 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. 52
Accessing 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 this. Animal. weight another. Animal. country 53
Valid operations on a struct member depend only on its type this. Animal. age = 18; this. Animal. id = 2037581; cin >> this. Animal. weight; getline ( cin, this. Animal. species ); this. Animal. name = “giant panda”; this. Animal. genus[ 0 ] = toupper (this. Animal. genus[ 0 ] ) ; this. Animal. age++; 54
Aggregate 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. 55
Aggregate 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 56
Examples of aggregate struct operations another. Animal = this. Animal ; // assignment Write. Out(this. Animal); // value parameter Change. Weight. And. Age(this. Animal); // reference parameter this. Animal = Get. Animal. Data( ); // return value of function 57
void Write. Out( /* in */ Animal. Type this. Animal) // Prints out values of all members of this. Animal // Precondition: all members of this. Animal are assigned // Postcondition: all members have been written out { cout << “ID # “ << this. Animal. id << this. Animal. name << endl ; cout << this. Animal. genus << this. Animal. species << endl ; cout << this. Animal. country << endl ; cout << this. Animal. age << “ years “ << endl ; cout << this. Animal. weight << “ lbs. “ << endl ; cout << “General health : “ ; Write. Word ( this. Animal. health ) ; } 58 58
Passing a struct Type by Reference void Change. Age ( /* inout */ Animal. Type& this. Animal ) // Adds 1 to age // Precondition: // Postcondition: this. Animal. age is assigned this. Animal. age == this. Animal. age@entry + 1 { this. Animal. age++ ; } 59
Animal. Type Get. Animal. Data ( void ) // Obtains all information about an animal from keyboard // Postcondition: // Function value == Animal. Type members entered at kbd { Animal. Type this. Animal ; char response ; do { // have user enter all members until they are correct. . . } while (response != ‘Y’ ) ; return this. Animal ; } 60 60
Hierarchical 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. . . 61
struct Machine. Rec Information about each machine in a shop contains: an id. Number, a written description, the purchase date, the cost, and a history (including failure rate, number of days down, and date of last service). 62
struct Date. Type { int month ; int day ; int year ; }; // Assume 1. . 12 // Assume 1. . 31 // Assume 1900. . 2050 struct Statistics. Type { float fail. Rate ; Date. Type last. Serviced ; int down. Days ; }; // Date. Type is a struct type struct Machine. Rec { int id. Number ; string description ; Statistics. Type history ; Date. Type purchase. Date ; float cost ; }; // Statistics. Type is a struct type Machine. Rec machine ; 63 63
struct type variable machine 5719 “DRILLING…” . 02 1 25 1999 4 3 21 1995 8000. 0 . month. day. year. failrate . last. Serviced . id. Number. description. history . downdays. month. day. year . purchase. Date machine. history. last. Serviced. year has value 1999 . cost 64
C++ Data Types simple integral enum structured floating array struct union class char short int long bool float double long double address pointer reference 65
Unions in C++ Definition A union is a struct that holds only one of its members at a time during program execution. For Example union Weight. Type { long wt. In. Ounces ; int wt. In. Pounds; float wt. In. Tons; } ; only one at a time 66
Using Unions union Weight. Type { long wt. In. Ounces ; int wt. In. Pounds; float wt. In. Tons; } ; // declares a union type Weight. Type weight; // declares a union variable weight. wt. In. Tons = 4. 83 ; // Weight in tons is no longer needed. Reuse the memory space. weight. wt. In. Pounds = 35; 67
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 68
Control Abstraction Separates the logical properties of an action from its implementation. . . Search (list, item, length, where, found); . . . The function call depends on the function’s specification (description), not its implementation (algorithm) 69
Data 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? 70
Data Type set of values (domain) allowable operations on those values For example, data type int has domain operations -32768. . . 32767 +, -, *, /, %, >>, << 71
Abstract 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 72
Using typedef int Boolean; typedef char String 20 [21] ; String 20 message; // variable declarations Boolean senior. Citizen; 73
Using struct typedef char String 20 [ 21 ] ; struct Employee. Type { long String 20 int float // declares a struct data type id. Number ; name ; hours. Worked ; num. Dependents ; hourly. Wage ; data members }; Employee. Type my. Self; // declares variable 74
my. Self . id. Number. name. hours. Worked. dependents. hourly. Wage 213456789 ‘B’ ‘a’ ‘r’ ‘b’ ‘a’ ‘r‘ ‘a’ ‘ ’ ‘ ’ ‘ ’ . . . 38 4 24. 50 75
Abstract 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. . . 76
ADT Specification Example TYPE Time. Type DOMAIN Each Time. Type 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 77
Another ADT Specification TYPE Complex. Number. Type 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 78
ADT 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 79
Information Hiding Class implementation details are hidden from the client’s view. This is called information hiding. Public functions of a class provide the interface between the client code and the class objects. client code specification abs trac bar tion rier implementation 80
Benefits 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. 81
Several Possible Representations of Time. Type 3 int variables 10 45 27 3 strings “ 10” “ 45” “ 27” 3 -element int array 10 45 27 Actual choice of representation depends on time, space, and algorithms needed to implement operations 82
Some Possible Representations of Complex. Number. Type struct with 2 float members -16. 2. real 5. 8. imag 2 -element float array -16. 2 5. 8 83
C++ Data Types simple integral enum structured floating array struct union class char short int long bool float double long double address pointer reference 84
class Time. Type Specification // Specification File ( timetype. h ) class Time. Type { // declares a class data type // does not allocate memory public : // 5 public function members void bool Set ( int hours , int mins , int secs ) ; Increment ( ) ; Write ( ) const ; Equal ( Time. Type other. Time ) const ; Less. Than ( Time. Type other. Time ) const ; private : }; int int // 3 private data members hrs ; mins ; secs ; 85
Use 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 86
Using 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. 87
Member 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. 88
Client Code Using Time. Type #include “timetype. h” using namespace std ; int main ( ) { Time. Type bool current. Time ; end. Time ; done = false ; // includes specification of the class // declares 2 objects of Time. Type current. Time. Set ( 5, 30, 0 ) ; end. Time. Set ( 18, 30, 0 ) ; while ( ! done ) {. . . }; current. Time. Increment ( ) ; if ( current. Time. Equal ( end. Time ) ) done = true ; } 89 89
class 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. 90
C++ 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. 91
Aggregate 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 92
2 separate files Generally Used for class Type // Specification File ( timetype. h ) // Specifies the data and function members. class Time. Type { public: . . . private: . . . }; // Implementation File ( timetype. cpp ) // Implements the Time. Type member functions. . 93
Implementation File for Time. Type // Implementation File ( timetype. cpp ) // Implements the Time. Type member functions. #include “ timetype. h” // also must appear in client code #include <iostream>. . . bool Time. Type : : Equal ( /* in */ Time. Type other. Time ) const // Postcondition: // Function value == true, if this time equals other. Time // == false , otherwise { return ( (hrs == other. Time. hrs) && (mins == other. Time. mins) && (secs == other. Time. secs) ) ; } . . . 94
Member 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 out. File ; out. File. open (“a: \my. out”) ; class type . . . out. File. close( ) ; variable, object, instance 95
Familiar 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 (some. Char) ; cin. ignore (100, ‘n’) ; The statements below, declare my. Infile as an instance of class ifstream and invoke function member open ifstream my. Infile ; my. Infile. open ( “A: \mydata. dat” ) ; 96
Scope 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 current. Time. Write( ) ; number. Z. Write( ) ; // class Time. Type // class Complex. Number. Type In the implementation file, the scope resolution operator is used in the heading before the function member’s name to specify its class void Time. Type : : Write ( ) const { } . . . 97
Time. Type Class Instance Diagrams current. Time Set Increment Write Less. Than Equal end. Time Private data: hrs 17 mins 58 secs 2 Increment Write Less. Than Private data: hrs 18 mins 30 secs 0 Equal 98
Use 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) 99
Example Using const with a Member Function void Time. Type : : Write ( ) const // Postcondition: Time has been output in form HH: MM: SS { } if ( hrs < 10 ) cout << ‘ 0’ ; cout << hrs << ‘: ’ ; if ( mins < 10 ) cout << ‘ 0’ ; cout << mins << ‘: ’ ; if ( secs < 10 ) cout << ‘ 0’ ; cout << secs ; 100
Class 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 101
Specification of Time. Type Class Constructors class Time. Type // timetype. h { public : // 7 function members void Set ( int hours , int minutes , int seconds ) ; void Increment ( ) ; void Write ( ) const ; bool Equal ( Time. Type other. Time ) const ; bool Less. Than ( Time. Type other. Time ) const ; Time. Type ( int init. Hrs , int init. Mins , int init. Secs ) ; // constructor Time. Type ( ) ; private : int int }; // default constructor // 3 data members hrs ; mins ; secs ; 102
Implementation of Time. Type Default Constructor Time. Type : : Time. Type ( ) // Default Constructor // Postcondition: // hrs == 0 && mins == 0 && secs == 0 { hrs = 0 ; mins = 0 ; secs = 0 ; } 103
Implementation of Another Time. Type Class Constructor Time. Type : : Time. Type ( /* in */ int init. Hrs, /* in */ int init. Mins, /* in */ int init. Secs ) // Constructor // Precondition: 0 <= init. Hrs <= 23 && 0 <= init. Mins <= 59 // 0 <= init. Secs <= 59 // Postcondition: // hrs == init. Hrs && mins == init. Mins && secs == init. Secs { hrs = init. Hrs ; mins = init. Mins ; secs = init. Secs ; } 104
Automatic invocation of constructors occurs Time. Type departure. Time ; Time. Type movie. Time (19, 30, 0 ) ; // default constructor invoked // parameterized constructor departure. Time Set Increment Write Less. Than Equal movie. Time Set Private data: hrs 0 mins 0 secs 0 Increment Write Less. Than Equal Private data: hrs 19 mins 30 secs 0 105
Separate Compilation and Linking of Files specification file main program timetype. h client. cpp implementation file timetype. cpp #include “timetype. h” Compiler client. obj timetype. obj Linker client. exe 106
Avoiding 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 107
Example Using Preprocessor Directive #ifndef // timetype. h // Specification File #ifndef TIME_H #define TIME_H class Time. Type { public: . . . FOR COMPILATION THE CLASS DECLARATION IN FILE timetype. h WILL BE INCLUDED ONLY ONCE // timetype. cpp // Implementation File // client. cpp // Appointment program #include “timetype. h” . . . int main ( void ) { private: . . . } }; #endif 108
The End Next Lecture More about classes. How to create and use them. 109
- Slides: 109