Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

C++ Data Types

CS122 Algorithms and Data Structures


simple structured

integral enum floating array struct union class

MW 11:00 am - 12:15 pm, MSEC 101


char short int long bool
Instructor: Xiao Qin
Lecture 3: Structured Types and Classes float double long double address

pointer reference

aStudent anotherStudent

.id 9004267 .id 9003421

.firstname “David” .firstname “John”

.lastname “Smith” .lastname “Powell”

.school “NMT” .school “UNL”

.major “CS” .major “IT”

.age 18 .age 19

.weight 156.6 .weight 178.5

.health Good .health Excellent


3 4

1
struct StudentType struct type Declaration
enum HealthType { Poor, Fair, Good, Excellent } ; SYNTAX
struct StudentType // declares a struct data type
{ // does not allocate memory struct TypeName // does not allocate memory
long id ;
string firstname; {
string lastname; DataType MemberName ;
string school; struct members
string major;
DataType MemberName ; MemberList
int age;
float weight;
HealthType health;
}; };
StudentType aStudent; // declare variables of
AnimalType
StudentType anotherStudent;
5 6

Accessing struct Members Aggregate Operation


Dot ( period ) is the member selection


is an operation on a data structure as a




operator.
whole, as opposed to an operation on
an individual component of the data
EXAMPLES structure
StudentType aStudent, anotherStudent; //
declare variables . .of AnimalType
.
.
aStudent.weight
anotherStudent.country
7 8

2
Examples of
Aggregate struct Operations aggregate struct operations
anotherStudent = aStudent; //
I/O, arithmetic, and comparisons of entire assignment


struct variables are NOT ALLOWED! PrintStudentData(aStudent);


//alue parameter
operations valid on an entire struct type


ChangeAge(aStudent); // r
variable: assignment to another struct eference pter
variable of same type, pass to a function as
aStudent = GetStudentData( ); // return
argument (by value or by reference), return as
value of function
value of a function

9 10

void PrintStudentData( StudentType aStudent)


Passing a struct Type by Reference
// Prints out values of all members of aStudent
// Precondition: all members of aStudent are assigned
void ChangeAge (StudentType& aStudent ) /* inout */
// Postcondition: all members have been written out
{ // Adds 1 to age
cout << “ID # “ << aStudent.id; // Precondition: aStudent.age is assigned
cout << aStudent.firstname << aStudent.lastname << endl; // Postcondition: aStudent.age = aStudent.age@entry + 1

cout << aStudent.school << aStudent.major << endl; {

aStudent.age++ ;
cout << aStudent.age << “years “ << endl;
}
cout << aStudent.weight << “ lbs. “ << endl;

cout << “General health : “ ;

PrintWord ( aStudent.health ) ;
}
11 12

3
StudentType GetStudentData ( void )
// Obtains all information about a student from keyboard
Hierarchical Structures
// Postcondition:
// Function value = StudentType members entered at kbd The type of a struct member can be another
{ struct type. This is called nested or
StudentType aStudent ; hierarchical structures.
char response ;
do { // have user enter all members until they are correct

} while (response != ‘Y’ ) ;


return aStudent ;
}
13 14

struct DateType
{ int month ; // Assume 1 . . 12
struct MachineRec int day ;
int year ;
// Assume 1 . . 31
// Assume 1900 . . 2050
};
Information about each machine in a shop


struct StatisticsType
contains: { float failRate ;
– an idNumber, DateType lastServiced ; // DateType is a struct type
int downDays ;
– a written description, };
struct MachineRec
– the purchase date,
{ int idNumber ;
– the cost, string description ;
StatisticsType history ; // StatisticsType is a struct type
– and a history (including failure rate, number of days DateType purchaseDate ;
down, and date of last service). float cost ;
};
15 MachineRec machine ; 16

4
struct type variable machine Unions in C++
DEFINITION
A union is a struct that holds only one of its
members at a time during program execution.
361 “drilling…” .02 1 25 1999 4 3 21 1995 8000.0
.month .day .year EXAMPLE
.failrate .lastServiced .downdays .month .day .year
union WeightType
.description . history .purchaseDate .cost {
long wtInOunces ;
.idNumber int wtInPounds; only one at a time
float wtInTons;
machine.history.lastServiced.year has value 1999 } ;
17 18

Using Unions Data Abstraction


union WeightType // declares a union type
{
separates the logical properties of a


long wtInOunces ;
int wtInPounds; data type from its implementation
float wtInTons;
} ;

WeightType weight; // declares a union variable LOGICAL PROPERTIES IMPLEMENTATION


weight.wtInTons = 4.83 ; What are the possible values? How can this be done in C++?
// Weight in tons is no longer needed. Reuse the memory space.
What operations will be needed? How can data types be used?
weight.wtInPounds = 35;

19 20

5
Abstract Data Type (ADT) ADT Specification Example
TYPE
TimeType
A data type whose domain and operations are


DOMAIN
specified (what) independently of any
particular implementation (how). Each 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
21 22

Another ADT Specification To implement an ADT means


TYPE
ComplexNumberType
choosing a specific data representation


DOMAIN
Each value is an ordered pair of real numbers (a, b) for the ADT using existing data types
representing a + bi. (built-in or programmer-defined), and
OPERATIONS
Initialize the complex number
Write the complex number 

writing functions for each ADT operation.


Add
Subtract
Multiply
Divide
Determine the absolute value of a complex number
23 24

6
Several Possible Representations of Some Possible Representations
TimeType of ComplexNumberType
3 int variables struct with 2 float members
10 45 27
-16.2 5.18
3 strings
real .imag
“10” “45” “27”

3-element int array


2-element float array
10 45 27

actual choice of representation depends on -16.2 5.8


time, space, and algorithms needed to
implement operations
25 26

C++ Data Types Creating a Class


A class is like a type: we can create instances
of this type
simple structured class CookieType {
public:
void initToEmpty(); //Initialize the cookie to be empty
integral enum floating array struct union class void add(int n); // Add n units to the cookie
void quantity() const; // Return the current numbers of cookies

char short int long bool private:


int numUnits;
};
float double long double address
One can now declare:
CookieType cookie1;
pointer reference CookieType cookie2;

7
More about Class Using class
A class is a programmer-defined type whose


Each instance of CookieType is different


components (called class members) can be
– cookie1's copy of numUnits is not the same
copy as the one for cookie2. variables or functions.
Class members are private by default.


– Both copies may have different values


– The functions will act on the correct data Compiler does not permit client code to
access private class members.
We can create as many instances as needed
Class members declared public form the


Built in operations (such as addition,


interface between the client code and the
subtraction) cannot be applied to user defined
private class members.
classes
In most classes, the private members contain


Two operations are valid


data, and the public members are functions to
– Member selection: (.)
manipulate that data.
– Assignment (=)
30

class TimeType Specification Use of C++ data type class


// SPECIFICATION FILE ( timetype.h )
class TimeType { // declares a class data type Facilitates re-use of C++ code for an ADT.


// does not allocate memory


public : // 5 public function methods 

Software that uses the class is called a client.


void Set ( int hours , int mins , int secs ) ;
void Increment ( ) ;
Variables of the class type are called objects


void Write ( ) const ;


Boolean Equal ( TimeType otherTime ) const ; or instances of the class.
Boolean LessThan ( TimeType otherTime ) const ;
private : // 3 private data members
Client code uses public member functions to


int hrs ;
int mins ; handle its class objects.
int secs ;
};
31 32

8
Member functions
categorized by task class type declaration
The class declaration creates a data type and


CONSTRUCTOR -- a member function that


actually creates a new object and initialized some names the members of the class.
or all of its data members

It does not allocate memory for any variables




ACCESS FUNCTION or OBSERVER -- a member


function that can inspect (use but not modify) the of that type!
data members of a class without changing their
values. Such a function is declared with const
Client code still needs to declare class


follwing the parameter list in both the specification


and the implementation files. variables.

33 34

C++ Data Type class represents 2 separate files generally used for
an ADT class type
// SPECIFICATION FILE ( timetype .h )
2 kinds of class members: // Specifies the data and function members.
– data members and function members
class TimeType {
public:
class members are private by default . . .
data members are generally private private:
. . .
function members are generally declared public };

private class members can be accessed only by the


class member functions (and friend functions), not by // IMPLEMENTATION FILE ( timetype.cpp )
client code. // Implements the TimeType member functions

35 36

9
Implementation file for
TimeType Member selection operator .
// IMPLEMENTATION FILE ( timetype.cpp )
// Implements the TimeType member functions When a client uses a public member function, the
#include “ timetype.h” // also must appear in client code
function call requires a dot preceded by the name
#include <iostream.h> of the object. You can think of the function call as
 being sent to this object.
Boolean TimeType :: Equal (TimeType otherTime ) const
// POST: FCTVAL == true, if this time equals otherTime ofstream outFile ;
// == false , otherwise
{
return ( (hrs == otherTime.hrs) && (mins == otherTime.mins) outFile.open (“a:\\my.out”) ;
&& (secs == otherTime.secs) ) ; variable,
} object,
instance
. . . outFile.close( ) ;
class
37 type 38

TimeType Class Instance Diagrams


Familiar Class Instances
The member selection operator ( . ) selects either data
members or function members. currentTime endTime
Header files iostream.h and fstream.h declare the istream,
ostream,and ifstream, ofstream I/O classes. Set
Set
Both cin and cout are class objects and get and ignore Private data: Private data:
Increment Increment
are function members. hrs 17 hrs 18
Write Write
mins 58 mins 30
cin.get (someChar) ; LessThan LessThan
secs 2 secs 0
cin.ignore (100, ‘\n’) ; Equal
Equal

39 40

10
const member functions A const member function
void TimeType :: Write ( ) const
When a member function does not modify the // POST: Time has been output in form HH:MM:SS
private data members, use const in both the { if ( hrs < 10 )
function prototype (in specification file) and the cout << ‘0’ ;
heading of the function definition (in cout << hrs << ‘:’ ;
implementation file). if ( mins < 10 )
cout << ‘0’ ;
cout << mins << ‘:’ ;
if ( secs < 10 )
cout << ‘0’ ;
cout << secs ;
41 } 42

Separate Compilation and


Linking of Files Array of class objects
specification file
main program timetype.h implementation file const int MAX_SIZE = 50 ;
// declare array of class objects
client.cpp timetype.cpp
#include “timetype.h” TimeType trainSchedule[ MAX_SIZE ] ;

Compiler Compiler

client.obj timetype.obj The default constructor, if there is any constructor,


is invoked for each element of the array.

Linker

client.exe 43 44

11
Aside from . and = operator+ implemented as
a member function
Other operators like +, -, ==, * cannot be


JarType JarType :: operator+ ( /* in */ JarType otherJar )


used by a class unless they are first defined const
as either member functions or friends of the // POST: FCTVAL == this Jar + otherJar
class. // with combined number of units
{


The name of the function defining == must be int resultUnits = numUnits + otherJar.numUnits ;
operator == JarType resultJar (resultUnits) ; // invokes
constructor


The name of the function defining + must be return resultJar ;


operator + }

45 46

2 ways to use overloaded


operator+
// CLIENT CODE ( mainprog.cpp )
. . .
JarType myJar ( 10 ) ;
JarType yourJar ( 56 ) ;
JarType thirdJar ;

thirdJar = myJar + yourJar ; // uses familiar notation





thirdJar = myJar.operator+ (yourJar) ; // member notation

47

12

You might also like