PowerPoint Slides for Starting Out With C++ Eearly Objects ...

103
Chapter 13 Introduction to Classes Fall 2020 The Borough of Manhattan Community College

Transcript of PowerPoint Slides for Starting Out With C++ Eearly Objects ...

Chapter 13

Introduction to Classes

Fall 2020The Borough of Manhattan

Community College

Abstract Data Types

•Abstraction: a definition that captures general

characteristics without details

ex: An abstract triangle is a 3-sided polygon. A

specific triangle may be scalene, isosceles, or

equilateral

•Data Type: defines the kind of values that can be

stored and the operations that can be performed

on the values

Abstraction in Software Development

•Abstraction allows a programmer to design a

solution to a problem and to use data items

without concern for how the data items are

implemented

•This has already been encountered in the book:

–To use the pow function, you need to know what

inputs it expects and what kind of results it produces

–You do not need to know how it works

Abstract Data Types

•Abstract data types are programmer-created

data types that specify

–the legal values that can be stored

–the operations that can be done on the values

•The user of an abstract data type (ADT) does not

need to know any implementation details (e.g.,

how the data is stored or how the operations on it are

carried out)

Object-Oriented Programming

•Procedural programming uses variables to store

data, and focuses on the processes/actions that

occur in a program. Data and functions are

separate and distinct

•Object-oriented programming is based on

objects that encapsulate both data and the

functions that operate on the data

Object-Oriented Programming

Terminology 1 of 2

•object: software entity that combines data and functions that act on the data in a single unit

•attributes or member variables: the data items of an object

•methods, behaviors or member functions: procedures / functions that act on the attributes of the class

•encapsulation: the bundling of an object’s data and procedures into a single entity

Object-Oriented Programming

Terminology 2 of 2

•data hiding: restricting data access to members of an object. The intent is to allow only member functions to directly access and modify the object’s data

•public interface: members of an object that are available outside of the object. This allows the object to provide access to some data and functions without sharing its internal details and design, and provides some protection from data corruption

Object Example

Square

Square object’s data item: side

Square object’s functions: setSide - set the size of the side of the

square, getSide - return the size of the side of the square

Introduction to Classes 1 of 2

•Class: a programmer-defined data type used to define objects

• It is a pattern for creating objects

ex:

Vehicle v1, v2;

This creates two objects of the Vehicle class

Introduction to Classes 2 of 2

•Class declaration format:

class className{

declaration;declaration;

};

Access Specifiers

•Used to control access to members of the class

•Each member is declared to be either

public: can be called by or accessed by any

function inside or outside of the classor

private: can only be called by or accessed by functions that are members of the class

Class Example

class Square{private:int side;

public:void setSide(int s){ side = s; }int getSide(){ return side; }

};

More on Access Specifiers

•Can be listed in any order in a class

•Can appear multiple times in a class

• If not specified, the default is private

Creating and Using Objects

•Objects are instances of a class. They are

created with a definition statement after the class

has been declared

•A class declaration is similar to the blueprint for a

house. The blueprint itself is not a house, but is a

detailed description of a house

Creating and Using Objects

Creating and Using Objects

•An object is an instance of a class

• It is defined just like other variables

Square sq1, sq2;

•We can access members using dot operator

sq1.setSide(5);

cout << sq1.getSide();

Class Example

Types of Member Functions

•Accessor, or getter function: uses but does

not modify a member variable

ex: getSide

•Mutator, or setter function: modifies a member

variable

ex: setSide

Defining Member Functions

•Member functions are part of a class declaration

•You can place entire function definition inside the class declaration

or

•You can place just the prototype inside the class declaration and write the function definition after the class

Defining Member Functions Inside the Class

Declaration

•Member functions defined inside the class declaration are called inline functions

•Only very short functions, like the one below, should be inline functions

int getSide()

{ return side; }

Inline Member Function Example

class Square{

private:int side;

public:void setSide(int s){ side = s; }int getSide(){ return side; }

};

Defining Member Functions After the Class

Declaration

•Use a function prototype in the class declaration

•After declaring the class, define the function by preceding its name with the class name and the scope resolution operator (::)

int Square::getSide()

{

return side;

}

Class Example

Conventions

Member variables are usually private

Accessor and mutator functions are usually public

Use ‘get’ in the name of accessor functions,

‘set’ in the name of mutator functions

Class Example

• const appearing after the parentheses in a member

function declaration specifies that the function will not change any data in the calling object.

Program 13-1 (Continued)

Program 13-1 (Continued)

Program 13-1 (Continued)

Checkpoint

Which of the following shows the correct use of the scope resolution operator in a member function definition?

A. BankAccount::void setBalance(int amt)

B. void BankAccount::setBalance(int amt)

Checkpoint

An object’s private member variables can be accessed from outside the object by

A. public member functions

B. the dot (.) operator

C. any function

D. the main function

Checkpoint

Assume that account101 is an instance of the BankAccount class, which of the following is a valid call to the setBalancemember function?

A. setBalance(500);

B. account101::setBalance(500);

C. account101.setBalance(500);

D. BankAccount.setBalance(500);

Avoiding Stale Data

• Some data is the result of a calculation

• In the Rectangle class the area of a rectangle is calculated

– length x width

• If we were to use an area variable in the Rectangleclass, its value would be dependent on the length and the width

• If we change length or width without updating area, then area would become stale

• To avoid stale data, it is best to calculate the value of that data within a member function rather than store it in a variable

Constructors

•A constructor is a member function that is automatically called when an object of the class is created

It can be used to initialize data members

It must be a public member function

It must be named the same as the class

It must have no return type

Constructor – Examples

Inline Declaration outside the class

Constructor – Example

Constructor - Example

Overloading Constructors

•A class can have more than 1 constructor

•Overloaded constructors in a class must have different parameter lists

Square();

Square(int);

The Default Constructor

•Constructors can have any number of parameters, including none

•A default constructor is one that takes no arguments either due to

–No parameters

or

–All parameters have default values

Default Constructor Example

class Square{private:int side;

public:Square() // default { side = 1; } // constructor

// Other member // functions go here

};

Another Default Constructor Example

class Square{private:int side;

public:Square(int s = 1) // default { side = s; } // constructor

// Other member // functions go here

};

Only One Default Constructor

•Do not provide more than one default constructor

for a class: one that takes no arguments and one

that has default arguments for all parameters

Square();

Square(int = 0); // will not compile

Invoking a Constructor

•To create an object using the default constructor, use no argument list and no ()

Square sq1;

•To create an object using a constructor that has parameters, include an argument list

Square sq2(8);

• If a class has any programmer-defined constructors, it should have a programmer-defined default constructor

In-Place Initialization

• If you are using C++11 or later, you can initialize a

member variable in its declaration statement, just as you

can with a regular variable.

• This is known as in-place initialization. Here is an

example:

class Rectangle{private:

double width = 0.0;double length = 0.0;

public:Public member functions appear here…

};

Destructor

• Is a public member function automatically called

when an object is destroyed

The destructor name is ~className, e.g.,

~Square

It has no return type

It takes no arguments

Only 1 destructor is allowed per class(i.e., it cannot be overloaded)

Destructor - Example

Checkpoint

Constructor functions have the same name as the

A. class

B. class instance

C. program

Checkpoint

A constructor that requires no arguments is called

A. a null constructor

B. an inline constructor

C. a default constructor

Checkpoint

True or false: Like any C++ function, a constructor may be overloaded, providing each constructor has a unique parameter list

A. True

B. False

Checkpoint

True or false: Just as a class can have multiple constructors, it can also have multiple destructors

A. True

B. False

Checkpoint

What will the following program display on the screen?

5020

Checkpoint

What will the following program display on the screen?

47goodbyegoodbye

Private Member Functions

•A private member function can only be

called by another member function of the

same class

• It is used for internal processing by the class,

not for use outside of the class

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 the

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

Passing Objects to Functions

Notes on Passing Objects 1 of 2

•Using a value parameter for an object can slow down a program and waste space

•Using a reference parameter speeds up the program. However, it allows the function to modify the data of the object (argument) in the calling part of the program. This may not be desirable

Notes on Passing Objects 2 of 2

•To save space and time while protecting parameter data that should not be changed, use a const reference parameter in the function header:

void showData(const Square &sq){...}

• In order for the showData function to call Square member functions, those functions must use const in their prototype and header:

int Square::getSide() const{...}

Returning an Object from a Function

• A function can return an object

Square initSquare(); // prototype

Square s1 = initSquare(); // call

•initSquare() Example

Square initSquare()

{

Square sq; // local object

int size;

cout << "Enter the length of side: ";

cin >> size;

sq.setSide(size);

return sq;

}

Checkpoint

When an object is passed to a function, a copy of it is made if the object is

A. passed by value

B. passed by reference

C. passed by constant reference

Checkpoint

True or false: When an object is passed to a function, but the function is not supposed to change it, it is best to pass it as a constant reference

A. True

B. False

Constructor Initializer List

• An alternative approach for initializing data members in a

constructor, coming after a colon and consisting of a

comma-separated list of variableName(initValue) items

//Using statements in the constructor

Student::Student() {

name = "Yu Chen";

gpa = 3.25; }

//Using a constructor initializer list

Student::Student() : name("Yu Chen"),

gpa(3.25) {}

Object Composition 1 of 2

•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.

•Example: Define a rectangle class.

Then, define a carpet class and use a rectangle

object as a member of a carpet object.

Object Composition 2 of 2

Checkpoint

Assume a Map class has a member variable named positionthat is an instance of the Location class. The Location class has a private member variable named latitude and a public member function called getLatitude. Which of the following lines of code would correctly get and return the value stored in latitude?

A. return Location.latitude;

B. return Location.getLatitude();

C. return position.latitude;

D. return position.getLatitude();

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.

Using Separate Files

•Place class declaration in a header file that serves as the class specification file. Name the file classname.h (for example, Square.h)

•Place 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 that uses the class must #includethe class specification file and be compiled and linked with the class implementation file

Rectangle.h

Rectangle.cpp

Program.cpp

Include Guards

•Are 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

Rectangle.h

Focus on Problem Solving and Program

Design: An OOP Case Study

• You are a programmer for the Home Software Company.

You have been assigned to develop a class that models

the basic workings of a bank account.

• The class should perform the following tasks:

– Save the account balance.

– Save the number of transactions performed on the account.

– Allow deposits to be made to the account.

– Allow withdrawals to be taken from the account.

– Calculate interest for the period.

– Report the current account balance at any time.

– Report the current number of transactions at any time.

Account.h

Account.cpp

bankApp.cpp

bankApp.cpp

bankApp.cpp

bankApp.cpp

Focus on Object-Oriented Programming:

Simulating Dice with Objects

• Dice traditionally have six sides. Some games, however,

use specialized dice that have a different number of

sides. For example, the role-playing game Dungeons

and Dragons uses dice with four, six, eight, ten, twelve,

and twenty sides.

• Suppose you are writing a program that needs to roll

simulated dice with various numbers of sides. A simple

approach would be to write a Die class with a constructor

that accepts the number of sides as an argument. The

class would also have appropriate methods for rolling the

die and getting the die’s value.

Die.h

Die.cpp

gameApp.h

Focus on Object-Oriented Design: The

Unified Modeling Language (UML)

• Concept: The Unified Modeling Language (UML)

provides a standard method for graphically depicting an

object-oriented system.

• General layout of a UML diagram:

Focus on Object-Oriented Design: The

Unified Modeling Language (UML)

• Showing Access Specification in UML Diagrams:

–In a UML diagram you may optionally place a –

(minus) character before a member name to indicate

that it is private, or a + (plus) character to indicate

that it is public.

Focus on Object-Oriented Design: The

Unified Modeling Language (UML)

• Data Type and Parameter Notation in UML Diagrams:

–To indicate the data type of a member variable, or

the return type of a member function, place a colon

followed by the data type after the variable name, or

the function name.

Focus on Object-Oriented Design: The

Unified Modeling Language (UML)

• Showing Constructors and Destructors in a UML

Diagram:

–Constructors and destructors are shown just as any

other function, except they have no return type.

Introduction to Object-Oriented Analysis

and Design

•Object-Oriented Analysis: 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

Identify Classes and Objects

•Consider the major data elements and the operations on these elements

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 applicable to the problem

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

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

Relationships Between Classes

Possible relationships

• Access ("uses-a")

–allows an object to modify the attributes of another

object

• Ownership/Composition ("has-a")

–one object has another object as one of its

members

• Inheritance ("is-a")

–a class is based on another class. This means

that one class is a specialized case of the other

Finding the Classes: Case StudyWrite a description of the problem domain

• The problem domain is the set of real-world objects, parties, and major events related to the problem

Example:

Joe's Automotive Shop services foreign cars and specializes in servicing cars made by Mercedes, Porsche, and BMW. When a customer brings a car to the shop, the manager gets the customer's name, address, and telephone number. The manager then determines the make, model, and year of the car, and gives the customer a service quote. The service quote shows the estimated parts charges, estimated labor charges, sales tax, and total estimated charges.

Finding the Classes: Case StudyList the nouns, noun phrases, and pronouns

• The problem domain is the set of real-world objects, parties, and major events related to the problem

Example:

Joe's Automotive Shop services foreign cars and specializes in servicing cars made by Mercedes, Porsche, and BMW. When a customer brings a car to the shop, the manager gets the customer's name, address, and telephone number. The manager then determines the make, model, and year of the car, and gives the customer a service quote. The service quote shows the estimated parts charges, estimated labor charges, sales tax, and total estimated charges.

Finding the Classes: Case StudyRefine the list of nouns

• The list of all the nouns without duplicating any of them

• Some of the nouns really mean the same thing

Finding the Classes: Case StudyRefine the list of nouns

• Some nouns might represent items that we do not need to be concerned with in order to solve the problem

• Some of the nouns might represent objects, not classes

Finding the Classes: Case StudyRefine the list of nouns

• Some of the nouns might represent simple values that can be stored in a variable and do not require a class

• As you can see from the list, we have eliminated everything except cars, customer, and service quote

• This means that in our application, we will need classes to represent cars, customers, and service quotes. Ultimately, we will write a Car class, a Customer class, and a ServiceQuote class

Finding the Classes: Case Study Determine Class Responsibilities

Class responsibilities:

•What is the class responsible to know?

•What is the class responsible to do?

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