Nothing Special   »   [go: up one dir, main page]

Starting Out With Early Objects C Ninth

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

NINTH EDITION

1
C++

EARLY OBJECTS
by Tony Gaddis, Judy
Walters, and
Godfrey Muganda
Starting Out With
2
Topics

7.9 Passing Objects to Functions


7.10 Object Composition
7.11 Separating Class Specification,
Implementation, and Client Code
7.12 Structures
7.13 More About Enumerated Data Types
7.15 Introduction to Object-Oriented Analysis and
Design
7.16 Screen Control

3
7.9 Passing Objects to Functions

A class object can be passed as an argument


to a function.
When it is passed by value:
 The function makes a local copy of the object.
 The original object in calling environment is
unaffected by actions in the function.
When passed by reference:
 The function can use ‘set’ functions to modify the
object in the calling environment.
4
Notes on Passing Objects
Using a value parameter for an object can slow down a
program and waste space

Using a reference parameter speeds up the program. It


allows the function to modify data in the parameter,
which may not be desirable.

5
Notes on Passing Objects

To save space and time while protecting parameter data


that should not be changed, use a const reference
parameter
void showData(const Square &s)//header

In order to for the showData function to call


Square member functions, those functions must
use const in their prototype and header:
int Square::getSide() const;

6
Returning an Object from a Function

A function can return an object


Square initSquare(); // prototype
Square s1 = initSquare();// call

The function must create an object


 for internal use
 to use with return statement

7
Returning an Object Example

Square initSquare()
{
Square s; // local object
int inputSize;
cout << "Enter the length of side: ";
cin >> inputSize;
s.setSide(inputSize);
return s;
}

8
7.10 Object Composition

This occurs when an object is a member variable of


another object.
It is often used to design complex objects whose
members are simpler objects
ex. (from book): Define a rectangle class. Then, define a
carpet class and use a rectangle object as a member of a
carpet object.

9
Object Composition, cont.

10
7.11 Separating Class Specification,
Implementation, and Client Code

Separating the class declaration, member


function definitions, and the program that
uses the class into separate files is
considered good design.

11
Using Separate Files
Place the class declaration in a header file that
serves as the class specification file.
 Name the file classname.h (for example,
Square.h)
Place the member function definitions in a class
implementation file.
Name the file classname.cpp (for example,
Square.cpp)This file should #include the
class specification file.
A client program (client code) that uses the
class must #include the class specification
file and be compiled and linked with the class
implementation file. 12
Include Guard

Is used to prevent a header file from being included


twice
Format:
#ifndef symbol_name
#define symbol_name
. . . (normal contents of header file)
#endif
symbol_name is usually the name of the header
file, in all capital letters:
#ifndef SQUARE_H
#define SQUARE_H
. . .
#endif
13
What Should Be Done Inside vs. Outside
the Class
Class should be designed to provide functions to store
and retrieve data
In general, input and output (I/O) should be done by
functions that use class objects, rather than by class
member functions

14
7.12 Structures

Structure: A programmer-defined data type


that allows multiple variables to be grouped
together
Structure declaration format:
struct structureName
{
type1 field1;
type2 field2;

typen fieldn;
};

15
Example struct Declaration

struct Student structure name


{
int studentID;
string name;
short year; structure members

double gpa;
};
Note the
required
;
16
struct Declaration Notes
struct names commonly begin with an
uppercase letter
Multiple fields of same type can be
declared in a comma-separated list
string name,
address;
Fields in a structure are all public by
default

17
Defining Structure Variables

A struct declaration does not allocate memory or


create variables
To define variables, use structure tag as the type name
Student s1;

s1
studentID
name
year

gpa

18
Accessing Structure Members

Use the dot (.) operator to refer to the data members of


struct variables
getline(cin, s1.name);
cin >> s1.studentID;
s1.gpa = 3.75;
The member variables can be used in any manner
appropriate for their data type

19
Displaying struct Members

To display the contents of a struct variable, you must


display each field separately, using the dot operator
Wrong:
cout << s1; // won’t work!
Correct:
cout << s1.studentID << endl;
cout << s1.name << endl;
cout << s1.year << endl;
cout << s1.gpa;

20
Comparing struct Members

Similar to displaying a struct, you cannot compare two


struct variables directly:

if (s1 >= s2) // won’t work!

Instead, compare member variables:


if (s1.gpa >= s2.gpa) // better

21
Initializing a Structure (continued)

Structure members are initialized at the time a


structure variable is created
You can initialize a structure variable’s members with
either
 an initialization list
 a constructor

22
Using an Initialization List

An initialization list is an ordered set of values, separated


by commas and contained in { }, that provides initial
values for a set of data members

{12, 6, 3} // initialization list


// with 3 values

23
More on Initialization Lists
The order of list elements matters: The first value
initializes first data member, second value
initializes second data member, etc.
The elements of an initialization list can be
constants, variables, or expressions

{12, W, L / W + 1} // initialization list


// with 3 items

24
Initialization List Example

#include <iostream>

using namespace std;


Structure Declaration
struct Dimensions
{
int length, Structure Variable
width,
height;
}; box
int main() length 12
{
Dimensions box = { 12,6,3 };
cout << box.length << endl;
width 6
cout << box.width << endl;
cout << box.height << endl; height 3
system("pause");
}
25
Partial Initialization

You can initialize just some members,


but you cannot skip over members

Dimensions box1 = { 12,6 }; //OK


Dimensions box2 = { 12,,3 }; //illegal

26
Problems with an Initialization List
You can’t omit a value for a data member without omitting
values for all following members
It does not work on most modern compilers if the structure
contains objects, e.g., like string objects

27
Using a Constructor to Initialize Structure
Members

This is similar to a constructor for a class:


 the name is the same as the name of the struct
 it has no return type
 it is used to initialize data members
It is normally written inside the struct declaration

28
A Structure with a Constructor
struct Dimensions
{
int length,
width,
height;

Dimensions(int L, int W, int H) // Constructor


{
length = L;
width = W;
height = H;
}
};

29
Nested Structures

A structure can have another structure as a member.


struct PersonInfo
{
string name,
address,
city;
};

struct Student
{
int studentID;
PersonInfo pData;
short year;
double gpa;
};
30
Members of Nested Structures
Use the dot operator multiple times to access
fields of nested structures
Student s5;
s5.pData.name = "Joanne";
s5.pData.city = "Tulsa";
Reference the nested structure’s fields by the
member variable name, not by the structure
name
s5.PersonInfo.name = "Joanne"; //no!

31
Structures as Function Arguments

You may pass members of struct variables to


functions
computeGPA(s1.gpa);
You may pass entire struct variables to functions
showData(s5);
You can use a reference parameter if the function needs
to modify the contents of the structure variable

32
Notes on Passing Structures

Using a value parameter for structure can slow down a


program and waste space
Using a reference parameter speeds up program
execution, but it allows the function to modify data in the
structure
To save space and time while protecting structure data
that should not be changed, use a const reference
parameter
void showData(const Student &s)
// header

33
Returning a Structure from a Function
A function can return a struct
Student getStuData(); // prototype
s1 = getStuData(); // call
The function must define a local structure variable
 for internal use
 to use with return statement

34
Returning a Structure Example
Student getStuData()
{
Student s; // local variable
cin >> s.studentID;
cin.ignore();
getline(cin, s.pData.name);
getline(cin, s.pData.address);
getline(cin, s.pData.city);
cin >> s.year;
cin >> s.gpa;
return s;
}

35
7.13 Enumerated Data Types
#include <iostream>
#include <string>

using namespace std;

enum DAY
{
saturday = 0,
sunday = 0,
monday,
tuesday,
wednesday,
thursday,
friday
};

void main()
{

DAY day = monday;

if (day == 0)
cout << "Day is a weekend day" << endl;
else if (day == wednesday)
cout << "Day is middle of the work week" << endl;
else
cout << "Day is work day" << endl;
}

36
7.13 Enumerated
Data Types
Additional ways that enumerated data types can be used:
Data type declaration and variable definition in a single
statement:
enum Tree { ASH, ELM, OAK } tree1, tree2;
 Assign an int value to an enum variable:
 enum Tree { ASH, ELM, OAK } tree1;
tree1 = static_cast<Tree>(2); // ELM
cout << tree1 << endl;

37
7.13 More About Enumerated
Data Types
#include <iostream>

using namespace std;

enum Days { Saturday, Sunday, Tuesday, Wednesday, Thursday, Friday };

int main()
{

cout << Saturday << endl;

38
7.13 More About Enumerated
Data Types
#include <iostream>

using namespace std;

enum Days { Saturday, Sunday, Tuesday, Wednesday, Thursday, Friday };

int main()
{
Days day = Sunday;
if (day == Saturday) {
cout << "Ok its Saturday" << endl;
}
else
{
std::cout << "its not Saturday" << endl;
}
}

39
Strongly Typed enums (C++ 11)

Enumerated values (names) cannot be re-used


in different enumerated data types that are in the
same scope.
A strongly typed enum (an enum class) allows
you to do this
enum class Tree { ASH, ELM, OAK };
enum class Street { RUSH, OAK, STATE };
 Note the keyword class in the declaration

40
Strongly Typed enums (C++ 11)

Because enumerators can be used in multiple enumerated


data types, references must include the name of the
strongly typed enum followed by : :
enum class Tree : char {ASH, ELM, OAK};
Tree tree1 = Trees::OAK;

41
7.15 Introduction to Object-Oriented
Analysis and Design
Object-Oriented Analysis: that phase of program
development when the program functionality is
determined from the requirements
It includes
 identification of classes and objects
 definition of each class's attributes
 definition of each class's behaviors
 definition of the relationship between classes

42
Identify Classes and Objects

Consider the major data elements and the


operations on these elements
Candidates include
 user-interface components (menus, text boxes, etc.)
 I/O devices
 physical objects
 historical data (employee records, transaction logs,
etc.)
 the roles of human participants
43
Define Class Attributes

Attributes are the data elements of an object of the class


They are necessary for the object to work in its role in
the program

44
Define Class Behaviors

For each class,


 Identify what an object of a class should do in the program

The behaviors determine some of the member functions


of the class

45
Relationships Between Classes

Possible relationships
 Access ("uses-a")
 Ownership/Composition ("has-a")
 Inheritance ("is-a")

46
Finding the Classes

Technique:
Write a description of the problem domain (objects,
events, etc. related to the problem)
List the nouns, noun phrases, and pronouns.
 These are all candidate objects

Refine the list to include only those objects that are


relevant to the problem

47
Determine Class Responsibilities

Class responsibilities:
What is the class responsible to know?
What is the class responsible to do?

Use these to define some of the member functions

48
Object Reuse

A well-defined class can be used to create objects in


multiple programs
By re-using an object definition, program development
time is shortened
One goal of object-oriented programming is to support
object reuse

49
Object-Based vs. Object-Oriented

A program that uses classes and objects is


object-based.
An object-based program that
 defines relationships between classes of
objects
 creates classes from other classes
 determines member function behavior based
on the object
is more likely to be an object-oriented program

50
7.16 Screen Control

Programs to date have all displayed output starting at the


upper left corner of the computer screen or output
window.
 Output is displayed left-to-right, line-by-line.
Computer operating systems are designed to allow
programs to access any part of the computer screen.
Such access is operating system-specific.

51
Screen Control – Concepts

An output screen can be thought of as a grid of 25 rows


and 80 columns. Row 0 is at the top of the screen.
Column 0 is at the left edge of the screen.
The intersection of a row and a column is a cell. It can
display a single character.
A cell is identified by its row and column number.
 These are its coordinates.

52
Screen Control – Windows - Specifics

#include <windows.h> to access the operating system


from a program
Create a handle to reference the output screen:
HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE);
Create a COORD structure to hold the coordinates of a cell
on the screen:
COORD position;

53
Screen Control – Windows –
More Specifics
Assign coordinates where the output should appear:
position.X = 30; // column
position.Y = 12; // row
Set the screen cursor to this cell:
SetConsoleCursorPosition(screen, position);
Send output to the screen:
cout << "Look at me!" << endl;

54
55
56

You might also like