No Slide Title

Download Report

Transcript No Slide Title

1
An Overview of Object-Oriented
Programming and C++
Object-Oriented Programming
Using C++
Second Edition
1
Objectives
• In this chapter, you will learn:
• About the task of programming
• About programming universals
• About procedural programming
• About object-oriented programming
• About the C++ programming environment
• How to create a main() function
1
Objectives
• In this chapter, you will learn:
• How to work with variables and the const qualifier
• How to create comments
• How to use libraries and preprocessor directives
• How to use cout and cin
• How to work with classes
1
The Task of Programming
• Programming a computer involves writing
instructions that enable a computer to carry out a
single task or a group of tasks
• A computer programming language requires
learning both vocabulary and syntax
• Programmers use many different programming
languages, including BASIC, Pascal, COBOL,
RPG, and C++
• The rules of any language make up its syntax
• Machine language is the language that computers
can understand; it consists of 1s and 0s
1
The Task of Programming
• A translator (called either a compiler or an
interpreter) checks your program for syntax
errors
• A logical error occurs when you use a statement
that, although syntactically correct, doesn’t do
what you intended
• You run a program by issuing a command to
execute the program statements
• You test a program by using sample data to
determine whether the program results are
correct
1
Programming Universals
• All programming languages provide methods for
directing output to a desired object, such as a
monitor screen, printer or file
• Similarly, all programming languages provide
methods for sending input into the computer
program so that it can be manipulated
• In addition, all programming languages provide
for naming locations in computer memory
• These locations commonly are called variables
(or attributes)
1
Programming Universals
• Ideally, variables have meaningful names,
although no programming language actually
requires that they meet this standard
• A variable may have only one value at a time, but
it is the ability of memory variables to change in
value that makes computers and programming
worthwhile
• In many computer programming languages,
including C++, variables must be explicitly
declared, or given a data type as well as a name,
before they can be used
1
Programming Universals
• The type determines what kind of values may be
stored in a variable
• Most computer languages allow at least two
types: one for numbers and one for characters
• Numeric variables hold values like 13 or -6
• Character variables hold values like ‘A’ or ‘&’
• Many languages include even more specialized
types, such as integer (for storing whole
numbers) or floating point (for storing numbers
with decimal places)
1
Procedural Programming
• Procedural programs consist of a series of steps
or procedures that take place one after the other
• The programmer determines the exact conditions
under which a procedure takes place, how often it
takes place, and when the program stops
• Programmers write procedural programs in many
programming languages, such as COBOL, BASIC,
FORTRAN, and RPG
• You can also write procedural programs in C++
1
Early Procedural Programs
• When programming languages were first used,
the programmer’s job was to break a task into
small, specific steps
• Each step was then coded in an appropriate
language
• Three basic control structures are used in
procedural programming
• In the first structure, a sequence, program steps
execute one after another, without interruption
1
Early Procedural Programs
• Procedural programs also can include a second
control structure called selection, which you use
to perform different tasks based on a condition
1
Early Procedural Programs
• The third control structure used in computer
programs is the loop
• some programmers call the loop structure a
repetition or iteration structure
1
Adding a Loop to a Simple
Procedural Billing Program
1
Modularity and Abstraction
• Programming in the oldest procedural languages
had two major disadvantages:
– The programming process involved so much detail that
the programmer (and any person reading the program)
lost sight of the big picture
– Similar statements required in various parts of the
program had to be rewritten in more than one place
• Writing programs became easier when
programming languages began to allow the
programmer to write methods
• Using methods allows programmers to group
statements together into modules or routines
1
Modularity and Abstraction
1
The Procedural Billing Program
Containing Several Module Calls
1
Encapsulation
• Modules or procedures act somewhat like
relatively autonomous mini-programs
• Not only can modular routines contain their own
sets of instructions, but most programming
languages allow them to contain their own
variables as well
• The variables and instructions within a module
are hidden and contained —that is
encapsulated—which helps to make the module
independent of all other modules, and therefore
reusable
1
Object-Oriented Programming
• Object-oriented programming requires a different
way of thinking and adds several new concepts to
programming;
– You analyze the objects with which you are working—
both the attributes of those objects and the tasks that
need to be performed with and on those objects
– You pass messages to objects, requesting the objects to
take action
– The same message works differently when applied to
the various objects
1
Object-Oriented Programming
– A method can work appropriately with different types of
data it receives, without the need for separate method
names
– Objects can share or inherit traits of previously created
objects, thereby reducing the time it takes to create new
objects
– Information hiding is more complete than in procedural
programs
1
Object-Oriented Programming
• The basic principles behind using objectoriented programming techniques involve:
– Objects
– Classes
– Inheritance
– Polymorphism
1
Objects and Classes
• An object is any thing
• A class consists of a category of things
• An object is a specific item that belongs to a
class; it is called an instance of a class
• A class defines the characteristics of its objects
and the methods that can be applied to its objects
• It is conventional, but not required, to begin
object names with a lowercase letter, and to begin
class names with an uppercase letter
1
Inheritance
• The concept of using classes provides a
useful way to organize objects; it is especially
useful because classes are reusable or
extensible
• You can create new classes that extend or are
descendants of existing classes
• The descendent classes can inherit all the
attributes of the original (or parent) class, or
they can override inappropriate attributes
1
Polymorphism
• Programming modules might occasionally need to
change the way they operate depending on the
context
• Object-oriented programs use polymorphism to carry
out the same operation in a manner customized to the
object
• Without polymorphism you would have to use a
separate module or method name for a method that
multiplies two numbers and one that multiplies three
numbers
• Without polymorphism you would have to create
separate module names for a method that cleans a
Dish object, one that cleans a Car object, and one that
cleans a Baby object
1
Getting Started in the C++
Programming Environment
• Depending on your C++ installation, you can
access the compiler by clicking an icon, selecting
from a menu, or typing a command
• The main work area in any C++ programming
environment is the editor
• An editor is a simplified version of a word
processor in which you type your program
statements, or source code
• After you enter the source code for a program,
you must compile the program
1
Getting Started in the C++
Programming Environment
• When you compile, the code you have written is
transformed into machine language—the
language that the computer can understand
• The output from the compilation is object code
• When a C++ program is compiled, a file is created
that has the same filename as the source code,
but has the extension .obj
• A runnable, or executable, program needs the
object code as well as code from any outside
sources (other files) to which it refers
1
Getting Started in the C++
Programming Environment
• The process of integrating these outside
references is called linking
• An executable file contains the same filename as
the source code and the object code, but carries
the extension .exe to distinguish it as a program
• When you compile a C++ program, error
messages and/or warnings might appear
• A C++ program with errors will not execute; you
must eliminate all error messages before you can
run the program
1
Creating a main( ) Function
• C++ programs consist of modules called
functions
• Every statement within every C++ program is
contained in a function
• Every function consists of two parts:
– A function header is the initial line of code in a C++
which always has three parts:
• Return type of the function
• Name of the function
• Types and names of any variables enclosed in
parentheses, and which the function receives
– A function body
1
Creating a main( ) Function
• A C++ program may contain many functions, but
every C++ program contains at least one function,
and that function is called main( )
• If the main function does not pass values to other
programs or receives values from outside the
program, then main( ) receives and returns a void
type
• The body of every function in a C++ program is
contained in curly braces, also known as curly
brackets
1
Creating a main( ) Function
• Every complete C++ statement ends with a
semicolon
• Often several statements must be grouped
together, as when several statements must occur
in a loop
• In such a case, the statements have their own set
of opening and closing braces within the main
braces, forming a block
1
Working with Variables
• In C++, you must name and give a type to
variables (sometimes called identifiers) before
you can use them
• Names of C++ variables can include letters,
numbers, and underscores, but must begin with a
letter or underscore
• No spaces or other special characters are
allowed within a C++ variable name
• Every programming language contains a few
vocabulary words, or keywords, that you need in
order to use the language
1
Common C++ Keywords
1
Working with Variables
• A C++ keyword cannot be used as a variable
name
• Each named variable must have a type
• C++ supports three simple types:
– Integer
— Floating point
— Character
• An integer is a whole number, either positive or
negative
• An integer value may be stored in an integer
variable declared with the keyword int
• You can also declare an integer variable using
short int and long int
1
Working with Variables
• Real or floating-point numbers are numbers that
include decimal positions, such as 98.6,
1000.00002, and -3.85
• They may be stored in variables with type float,
double, and long double
• Characters may be stored in variables declared
with the keyword char
• A character may hold any single symbol in the
ASCII character set
• Often it contains a letter of the alphabet, but it
could include a space, digit, punctuation mark,
arithmetic symbol, or other special symbol
1
Working with Variables
• In C++, a character value is always expressed in
single quotes, such as ‘A’ or ‘&’
• To declare a variable, you list its type and its
name
• In addition, a variable declaration is a C++
statement, so it must end with a semicolon
• If you write a function that contains variables of
diverse types, each variable must be declared in
a statement of its own
• If you want to declare two or more variables of
the same type, you may declare them in the same
statement
1
Working with Variables
• Explicitly stating the value of a variable is called
assignment, and is achieved with the assignment
operator =
• The variable finalScore is declared and assigned
a value at the same time
• Assigning a value to a variable upon creation is
often referred to as initializing the variable
1
The const Qualifier
• A variable that does not change in a program
should not be declared as a variable
• Instead, it should be a constant
• The statement const double MINIMUM_WAGE
= 5.75; declares a constant named
MINIMUM_WAGE that can be used like a
variable, but cannot be changed during a
program
1
Creating Comments
• Comments are statements that do not affect the
compiling or running of a program
• Comments are simply explanatory remarks that
the programmer includes in a program to clarify
what is taking place
• These remarks are useful to later program users
because they might help explain the intent of a
particular statement or the purpose of the entire
program
• C++ supports both line comments and block
comments
1
Creating Comments
• A line comment begins with two slashes (//) and
continues to the end of the line on which it is placed
• A block comment begins with a single slash and an
asterisk (/*) and ends with an asterisk and a slash (*/);
it might be contained on a single line or continued
across many lines
1
Using Libraries and
Preprocessor Directives
• Header files are files that contain predefined
values and routines, such as squrt( )
• Their filenames usually end in .h
• In order for your C++ program to use these
predefined routines, you must include a
preprocessor directive, a statement that tells the
compiler what to do before compiling the
program
• In C++, all preprocessor directives begin with a
pound sign (#), which is also called an octothorp
• The #include preprocessor directive tells the
compiler to include a file as part of the finished
product
1
C++ Output
• C++ provides several objects for producing output
• The simplest object is called cout, pronounced “see
out”
• When contained in a complete C++ program, the
statement cout<<“Hi there”; places the phrase “Hi
there” on the monitor
1
C++ Output
• To indicate a newline character, you can use the
escape sequence \n
• Another way to advance output to a new line is to
use the end line manipulator endl
• Inserting endl into the output stream causes a
new line plus all waiting output to become visible,
a process called flushing the buffer
• To create a program that declares two variables,
assigns values to them, and creates output,
perform the steps on pages 21 to 23 of the
textbook
1
Program Listing for Output1.cpp
1
Output of Output1.cpp
1
C++ Input
• Many programs rely on input from a user
• These are called interactive programs because
the user interacts with the program statements
• You create prompts by using the cout object; you
retrieve user responses by using the cin object
• The cin (pronounced see in) object fetches values
from the keyboard
• It is used with the extraction operator >>
• Prior to a cin statement, it is almost always
necessary to provide the user with a prompt, or a
short explanation of what is expected
1
C++ Input
• Whitespace consists of any number of spaces,
tabs, and Enter characters
• You will add prompts and interactive input to the
Output1.cpp program by following the
instructions shown on pages 24 and 25 of the
textbook
1
Output of Output2.cpp
1
C++ Classes and Objects
• When you use data types like int, char, and
double within a program, you are using the C++
built-in, primitive or scalar data types
• A major feature of object-oriented languages is
the ability to create your own new, complex data
types
• These new types are called classes
• A class can contain many simpler data types
within it, as well as any number of functions
• The relationship between these components, or
fields, is often called a has-a relationship
1
C++ Classes and Objects
1
A Complete Class Definition
and a main( ) Method that
Uses a Class Object
1
C++ Classes and Objects
• You will create a Student class, and then create a
program that uses a Student class object using the
procedures outlined on pages 27 and 28 of the
textbook
• Creating a class provides a means to group data
fields together in a logical way
1
Summary
• Programming a computer involves learning the
syntax of a computer programming language and
resolving logical errors
• All programming languages provide methods for
input and output of variable values
• You declare a variable by providing it with a name
and a type
• Procedural programs consist of a series of steps
or procedures that take place one after the other
• Object-oriented programming adds several new
programming concepts including objects,
classes, inheritance, and polymorphism
1
Summary
• You write a C++ program by typing source code
into an editor and compiling the program
• C++ modules are called functions, and each
function contains a header and a body
• C++ variables must be given a type and a name
• Simple types include integer for whole numbers,
double and float for floating-point values, and
character for any character
• Comments are non-executing program
statements
1
Summary
• C++ supports line comments and block
comments
• A preprocessor directive tells the compiler to do
something, such as to include a header file,
before compiling the program
• The cout statement (along with an insertion
operator) is used to display values
• When you create a class, you create your own
C++ data type, which is a complex type
composed of simpler types