101
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 Data Structures Introduction to C++ Part II

Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Nirmalya Roy

School of Electrical Engineering and Computer ScienceWashington State University

Cpt S 122 – Data Structures

Introduction to C++Part II

Page 2: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Topics

Objectives

Defining class with a member function

Defining a member function with a parameter

Data member, set function and get function

Initializing objects with constructors

Placing Class in a separate file for reusability

Software reusability

Separating Interface from Implementation

Page 3: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Objectives

How to define a class and use it to create an object?

How to implement a class’s behaviors as member function?

How to implement class’s attributes as a data member?

How to call a member function of an object to perform a task?

How to use constructor to initialize an object’s data when object is created?

How to use object of class string?

Page 4: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

An example that consists of class GradeBook

Define a GradeBook object.

Function main uses this object and its member

function.

Member Function displayMessage()

display a message on the screen

Defining a Class with a Member Function

Page 5: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

GradeBook Class

Page 6: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

GradeBook Object

Page 7: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

The GradeBook class definition begins with keyword class Contains a member function called displayMessage

Make an object of class GradeBook Call its displayMessage member function

Function main is always called automatically when you execute a program.

Call member function displayMessage explicitly to tell it to perform its task.

Defining a Class with a Member Function (Cont.)

Page 8: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Defining a Class with a Member Function (Cont.)

The access-specifier label public: contains the keyword public is an access specifier.

Indicates that the function is “available to the public” can be called by other functions in the program (such as main)

by member functions of other classes (if there are any).

Access specifiers are always followed by a colon (:).

Page 9: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Defining a Member Function with Parameter

class GradeBook with a display-Message member function

displays the course name as part of the welcome message.

The new version of displayMessage requires a parameter (courseName ) that represents the course name to output.

A variable of type string represents a string of characters.

A string is actually an object of the C++ Standard Library class string. Defined in header file <string> and part of namespace std.

For now, you can think of string variables like variables of other types such as int.

Page 10: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Defining a Member Function with Parameter (Cont.)

Page 11: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Defining a Member Function with Parameter (Cont.)

Page 12: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Output

Page 13: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Defining a Member Function with Parameter

Library function getline reads a line of text into a string.

The function call getline( cin, nameOfCourse ) reads characters from the standard input stream object cin (i.e., the

keyboard).

places the characters in the string variable nameOfCourse

The <string> header file must be included in the program to use function getline.

Page 14: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

An object has attributes that are carried with it as it’s used

in a program.

Such attributes exist throughout the life of the object.

A class normally consists of one or more member functions

manipulate the attributes

Attributes are represented as variables in a class definition.

Such variables are called data members

Declared inside a class definition but outside the bodies of the

class’s member-function definitions.

Each object of a class maintains its own copy of its

attributes in memory.

Defining Data Members

Page 15: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Data Members, set Functions and get Functions (cont.)

Page 16: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Data Members, set Functions and get Functions (cont.)

Page 17: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Data Members, set Functions and get Functions (cont.)

Page 18: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Most data-member declarations appear after the access-specifier label private:

Like public, keyword private is an access specifier.

Variables or functions declared after access specifier private are accessible only to member functions of the class.

The default access for class members is private so all members after the class header and before the first access

specifier are private.

Private Data Members and Functions

Page 19: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Points to remember

Generally data members should be declared private

and member functions should be declared public.

An attempt by a function, which is not a member of a particular class (or a friend of that class) to access a private member of that class is a compilation error

Page 20: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Declaring data members with access specifier

private is known as data hiding.

When a program creates (instantiates) an object,

its data members are encapsulated (hidden) in the object.

accessed only by member functions of the object’s class.

Data Members (cont.)

Page 21: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

A client of an object any class or function that calls the object’s member functions from outside

the object.

Calls the class’s public member functions to request the class’s services.

Statements in main call member functions setCourseName, getCourseName and displayMessage on a GradeBook object.

Classes often provide public member functions to allow clients of the class to set (i.e., assign values to) or get (i.e., obtain the values of) private data members. These member function names need not begin with set or get.

Set functions are also sometimes called mutators mutate, or change, values

Get functions are also sometimes called accessors access values

Mutators and Accessors

Page 22: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Each class can provide a constructor

used to initialize an object of the class when the object is created.

A constructor is a special member function that must be defined with the same name as the class

compiler can distinguish it from the class’s other member functions.

An important difference between constructors and other functions

constructors cannot return values, so they cannot specify a return type (not even void).

Normally, constructors are declared public.

Initializing Objects with Constructor

Page 23: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Initializing Objects with Constructor

C++ requires a constructor call for each object that is

created

helps ensure that each object is initialized before it’s used in

a program.

The constructor call occurs implicitly when the object

is created.

If a class does not explicitly include a constructor

the compiler provides a default constructor.

a constructor with no parameters.

Page 24: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Initializing Objects with Constructor

Page 25: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Initializing Objects with Constructor

Page 26: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Initializing Objects with Constructor

Page 27: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Initializing Objects with Constructor

A constructor specifies in its parameter list the data it requires to perform its task.

When you create a new object, you place this data in the parentheses that follow the object name.

Constructor’s body passes the constructor’s parameter nameto member function setCourseName simply assigns the value of its parameter to data member

courseName.

Page 28: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Initializing Objects with Constructor

Creates and initializes a GradeBook object called

gradeBook1.

the GradeBook constructor is called (implicitly by

C++) with the argument "CS101 Introduction toC++ Programming"

initialize gradeBook1’s course name.

Page 29: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Initializing Objects with Constructor

Any constructor that takes no arguments is called a default constructor.

A class gets a default constructor in one of two ways: The compiler implicitly creates a default constructor in a class that

does not define a constructor. Such a constructor does not initialize the class’s data members, but does call the

default constructor for each data member

An uninitialized variable typically contains a “garbage” value.

You explicitly define a constructor that takes no arguments. Such a default constructor will call the default constructor for each data member

Perform additional initialization specified by you.

If you define a constructor with arguments, C++ will not implicitly create a default constructor for that class.

Page 30: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Observations

Data members can be initialized in a constructor.

Their values may be set later after the object is created.

Good software engineering practice

An object is fully initialized before the client code invokes the object’s member functions.

We should not rely on client code to ensure that an object gets initialized properly.

Page 31: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

One of the benefits of creating class definitions

classes can be reused by programmers.

potentially worldwide.

Programmers who wish to use our GradeBookclass cannot simply include the file in another

program.

function main begins the execution of every program,

every program must have exactly one main function.

Placing a Class in a Separate File for Reusability

Page 32: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Previous examples consists of a single .cpp file, known as a source-code file,

Contains a GradeBook class definition and

a main function.

In an object-oriented C++ program

define reusable source code (such as a class) in a file that by convention has a .h filename extension

known as a header file.

Programs use #include preprocessor directives to include header files

take advantage of reusable software components.

Placing a Class in a Separate File for Reusability

Page 33: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Separates the code into two files

GradeBook.h

the header file contains only the GradeBook class definition, the

appropriate header files and a using declaration.

XXX.cpp The main function that uses class GradeBook is defined in the source-

code file XXX.cpp

For the larger programs in industry, we often use a

separate source-code file containing function main to test

our classes

Known as a driver program.

Placing a Class in a Separate File for Reusability

Page 34: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Separate header file: GradeBook.h

Page 35: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Separate header file: GradeBook.h

Page 36: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Separate source code file: source.cpp

Page 37: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

A header file such as GradeBook.h cannot be used to begin program execution It does not contain a main function.

To test class GradeBook Need a separate source-code file containing a main function that

instantiates and uses objects of the class.

To help the compiler understand how to use a class, explicitly provide the compiler with the class’s definition

For example, to use type string, a program must include the <string> header file.

This enables the compiler to determine the amount of memory that it must reserve for each object of the class.

Placing a Class in a Separate File for Reusability

Page 38: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

The compiler creates only one copy of the class’s member functions shares that copy among all the class’s objects.

Each object, of course, needs its own copy of the class’s data members contents can vary among objects.

The member-function code, however, is not modifiable, so it can be shared among all objects of the class.

The size of an object depends on the amount of memory required to store the class’s data members.

Placing a Class in a Separate File for Reusability

Page 39: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Now that the class definition is in a header file

(without a main function),

we can include that header in any program that needs to

reuse our GradeBook class.

Placing a Class in a Separate File for Reusability

Page 40: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Notice that the name of the GradeBook.h header file in is enclosed in quotes (" ") rather than angle brackets (< >). Normally, a program’s source-code files and user-defined header files

are placed in the same directory.

When the preprocessor encounters a header file name in quotes, attempts to locate the header file in the same directory as the file in which the

#include directive appears.

If the preprocessor cannot find the header file in that directory, it searches for it in the same location(s) as the C++ Standard Library header files.

When the preprocessor encounters a header file name in angle brackets (e.g., <iostream>), it assumes that the header is part of the C++ Standard Library does not look in the directory of the program that is being preprocessed.

Placing a Class in a Separate File for Reusability

Page 41: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Placing a class definition in a header file reveals the entire implementation of the class to the class’s clients.

Conventional software engineering wisdom says that to use an object of a class, the client code needs to know only what member functions to call,

what arguments to provide to each member function,

what return type to expect from each member function,

client code does not need to know how those functions are implemented.

If client code does know how a class is implemented, the client-code programmer might write client code based on the class’s implementation details.

Ideally, if that implementation changes, the class’s clients should not have to change.

Hiding the class’s implementation details makes it easier to change the class’s implementation while minimizing, and hopefully eliminating,

changes to client code.

Separating Interface from Implementation

Page 42: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Interfaces define and standardize the ways in which

things such as people and systems interact with one

another.

The interface of a class describes what services a

class’s clients can use

how to request those services,

but not how the class carries out the services.

A class’s public interface consists of the class’s

public member functions (also known as the

class’s public services).

Separating Interface from Implementation

Page 43: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

In our prior examples, each class definition contained the complete definitions of the class’s public member functions and

the declarations of its private data members.

It’s better software engineering to define member functions outside the class definition, Their implementation details can be hidden from the client code.

Ensures that you do not write client code that depends on the class’s implementation details.

Separates class GradeBook’s interface from its implementation by splitting the class definition into two files the header file GradeBook.h in which class GradeBook is defined,

the source-code file GradeBook.cpp in which GradeBook’s member functions are defined.

Separating Interface from Implementation

Page 44: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

By convention, member-function definitions are

placed in a source-code file of the same base name

(e.g., GradeBook) as the class’s header file but

with a .cpp filename extension.

This three-file program is composed from the

perspectives of

the GradeBook class programmer and

the client-code programmer.

Separating Interface from Implementation

Page 45: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Header file GradeBook.h is similar to the earlier one,

Only the function definitions are replaced here with function prototypes describe the class’s public interface without revealing the class’s member-

function implementations.

A function prototype is a declaration of a function that tells the compiler the function’s name, its return type and the types of its parameters.

Include the header file GradeBook.h in the client code

provides the compiler with the information it needs to ensure that the client code calls the member functions of class GradeBookcorrectly.

Separating Interface from Implementation

Page 46: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Interface of the class (GradeBook.h file)

Page 47: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Source-code file GradeBook.cpp defines class GradeBook’s member functions.

Notice that each member-function name in the function headers is preceded by the class name and

::, which is known as the binary scope resolution operator.

This “ties” each member function to the (now separate) GradeBook class definition,

declares the class’s member functions and data members.

Implementation of the class

Page 48: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Implementation of the class (GradeBook.cpp)

Page 49: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Implementation of the class

Page 50: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

To indicate that the member functions in GradeBook.cppare part of class GradeBook,

we must first include the GradeBook.h header file.

This allows us to access the class name GradeBook in the GradeBook.cpp file.

When compiling GradeBook.cpp, the compiler uses the information in GradeBook.h to ensure that

the first line of each member function matches its prototype in the GradeBook.h file,

each member function knows about the class’s data members and other member functions

Separating Interface from Implementation

Page 51: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Implementation of the client code (main.cpp)

Page 52: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Before executing this program, the source-code files

must both be compiled, then linked together

the member-function calls in the client code need to be

tied to the implementations of the class’s member

functions

a job performed by the linker.

The diagram shows the compilation and linking

process that results in an executable GradeBookapplication.

Separating Interface from Implementation

Page 53: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Separating Interface from Implementation

Page 54: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

The C++ Standard Library is divided into many portions,

each with its own header file.

The header files contain the function prototypes for the

related functions that form each portion of the library.

The header files also contain definitions of various class

types and functions, as well as constants needed by those

functions.

A header file “instructs” the compiler on how to interface

with library and user-written components.

List of some common C++ Standard Library header files.

C++ Standard Library Header Files

Page 55: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Sometimes functions are not members of a class. Called global functions.

Function prototypes for global functions are placed in header files, the global functions can be reused in any program

The <cmath> header file provides a collection of functions enable you to perform common mathematical calculations.

Math Library Functions

Page 56: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Math Library Functions

Page 57: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Math Library Functions

Page 58: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

C++ Standard Library Header

Page 59: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

C++ Standard Library Header

Page 60: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

C++ Standard Library Header

Page 61: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

C++ Standard Library Header

Page 62: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

C++ Standard Library Header

Page 63: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

The element of chance can be introduced into computer applications by using the C++ Standard Library function rand.

The function rand generates an unsigned integer between 0 and RAND_MAX a symbolic constant defined in the <cstdlib> header file.

The value of RAND_MAX must be at least 32767 the maximum positive value for a two-byte (16-bit) integer.

For GNU C++, the value of RAND_MAX is 2147483647 Visual Studio, the value of RAND_MAX is 32767.

If rand truly produces integers at random, every number between 0 and RAND_MAX has an equal chance (or

probability) of being chosen each time rand is called.

Case Study: Random Number Generation

Page 64: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

The function prototype for the rand function is in

<cstdlib>.

To produce integers in the range 0 to 5, we use the

modulus operator (%) with rand: rand() % 6

This is called scaling.

The number 6 is called the scaling factor. Six values are

produced.

We can shift the range of numbers produced by

adding a value.

Case Study: Random Number Generation

Page 65: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Case Study: Random Number Generation

Page 66: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Output

Page 67: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

C++ provides inline functions to help reduce function call overhead especially for small functions.

Placing the qualifier inline before a function’s return type in the function definition “advises” the compiler to generate a copy of the function’s code in place (when appropriate) to avoid a function call.

Trade-off Multiple copies of the function code are inserted in the program

(often making the program larger)

Rather than there being a single copy of the function to which control is passed each time the function is called.

The complete function definition must appear before the code is inlined so that the compiler knows how to expand a function call into its inlined code.

Inline Functions

Page 68: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Inline Function

Page 69: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

It’s possible to declare local and global variables of

the same name.

C++ provides the unary scope resolution operator

(::) to access a global variable when a local

variable of the same name is in scope.

Using the unary scope resolution operator (::) with

a given variable name is optional when the only

variable with that name is a global variable.

Unary Scope Resolution Operator

Page 70: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Example: Unary Scope Resolution Operator

Page 71: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Test # 1 Statistics

Overall Highest 97

Section 1 Average: 77 (Highest 97)

Section 2 Average: 73 (Highest 92)

Section 3 Average: 73 (Highest 93)

Section 4 Average: 74 (Highest 97)

Section 5 Average: 75.50 (Highest 92)

Section 6 Average: 70 (Highest 97)

Page 72: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Constructors

Constructor is a special member function which enables an object to initialize itself when it is created

Name is same as the class name

Invoked whenever an object of its associated class is created

Constructs the values of the data members of the class

Destructor is a special member function that destroys the objects when they are no longer required

Page 73: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Constructors (Cont.)

class integer{

int m,n;

public:

integer (void); //constructor

…….

};

integer :: integer(void){ //constructor defined

m = 0; n = 0;

}

integer int1; // object int1 created

Page 74: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Constructors (Cont.)

Not only creates the object int1 of type integer

But also initializes its data members m and n to zero.

No need to invoke the constructor function.

A constructor that accepts no parameters is called a default constructor

The default constructor for class integer is class integer :: integer();

If no such constructor is defined then compiler supplies a default constructor.

Page 75: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Parameterized Constructors

class integer{

int m,n;

public:

integer (int x, int y); //parameterized constructor

…….

};

integer :: integer(int x, int y){ //constructor defined

m = x; n = y;

}

integer int1 (10, 100); //must pass the initial values

when object int1 is declared; implicit call

integer int1 = integer (10, 100); //explicit call

Page 76: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Multiple Constructors in a Class integer (); // No arguments

integer (int, int); // with arguments

class integer{

int m, n;

public:

integer (){ m = 0; n = 0;} //constructor 1

integer (int a; int b){ m = a; n = b;} //constructor 2

integer (integer & i){ m = i.m; n = i.n;} //constructor 3

};

integer I1; // object I1 created

integer I2 (20, 40); // object I2 created

integer I3 (I2); // object I3 created

copies the value of I2 into I3

sets the value of every data element of I3 to value of corresponding data

elements of I2.

copy constructor

Page 77: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Copy Constructor

A copy constructor is used to declare and initialize an object from another object

integer I3 (I2)

define object I3 and at the same time initialize it to the values of I2

Another form is: integer I3 = I2;

This process of initializing through a copy constructor is known as

copy initialization

I3 = I2 ??

Will not invoke the copy constructor

However I3 and I2 are objects; the statement is legal and simply

assign the values of I2 to I3; member by member.

This is the task of overloaded assignment operator ( = )

Page 78: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Destructors

Used to destroy the objects that have been created by a constructor

Like a constructor , the destructor is a member function whose name is the same name as the class name but is preceded by a tilde

For example, the destructor for class integer

~integer();

Destructor never takes any argument nor does it return any values Invoked implicitly by the compiler upon exit from the program to clean up

the storage

Good practice to declare destructors in a program as it releases memory space for future use

Page 79: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

C++ enables several functions of the same name to be

defined, as long as they have different signatures.

This is called function overloading.

The C++ compiler selects the proper function to call

examining the number, types and order of the arguments in the

call.

Overloaded functions are distinguished by their signatures.

A signature is a combination of a function’s name and its parameter types (in order).

Function overloading is used to create several functions of

the same name

perform similar tasks, but on different data types.

Function Overloading

Page 80: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Function Overloading

Page 81: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Example: Function Overloading

Page 82: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

The elements of an array can be initialized in the array declaration by following the array name

with an equals sign and a brace-delimited comma-separated list of initializers.

An initializer list to initialize an integer array with 10 values.

If there are fewer initializers than elements in the array

the remaining array elements are initialized to zero.

If the array size is omitted from a declaration with an initializer list,

the compiler determines the number of elements in the array by counting the number of elements in the initializer list.

Initializing an Array in a Declaration with an Initializer List

Page 83: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Initializer List

Page 84: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

If the program logic and operations are identical for

each data type

overloading may be performed more compactly and

conveniently by using function templates.

Why Function Templates?

Page 85: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

All function template definitions begin with the templatekeyword followed by a template parameter list to the function template enclosed in angle

brackets (< and >).

Every parameter in the template parameter list is preceded by keyword typename or keyword class.

The formal type parameters are placeholders for fundamental types or user-defined types.

These placeholders are used to specify the types of the function’s parameters, to specify the function’s return type and

to declare variables within the body of the function definition.

What is Function Template?

Page 86: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Example: Function Templates

Page 87: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Example: Function Templates

Page 88: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Example: Function Templates

Page 89: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

C++ Standard Library class template vector represents a more robust type of array featuring many additional capabilities.

C-style pointer-based arrays have great potential for errors and are not flexible

A program can easily “walk off” either end of an array, because C++ does not check whether subscripts fall outside the range of an array.

Two arrays cannot be meaningfully compared with equality operators or relational operators.

When an array is passed to a general-purpose function designed to handle arrays of any size, the size of the array must be passed as an additional argument.

One array cannot be assigned to another with the assignment operator(s).

Class template vector allows you to create a more powerful and less error-prone alternative to arrays.

C++ Standard Library Class Template vector

Page 90: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

The mext program example demonstrates capabilities

provided by class template vector.

Those are not available for C-style pointer-based arrays.

Standard class template vector is defined in header

<vector>

belongs to namespace std.

C++ Standard Library Class Template vector

Page 91: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Example: Template Vector

Page 92: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Example: Template Vector

Page 93: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Example: Template Vector

Page 94: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Example: Template Vector

Page 95: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Example: Template Vector

Page 96: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Example: Template Vector

Page 97: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Example: Template Vector

Page 98: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Example: Template Vector

Page 99: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

Example: Template Vector

Page 100: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

By default, all the elements of a vector object are set to 0.

vectors can be defined to store any data type.

vector member function size obtain the number of elements in the vector.

You can use square brackets, [], to access the elements in a vector.

vector objects can be compared with one another using the equality operators.

You can create a new vector object that is initialized with the contents of an existing vector by using its copy constructor.

C++ Standard Library Class Template vector

Page 101: Cpt S 122 Data Structures Introduction to C++ Part II+_Part2.pdf · A variable of type stringrepresents a string of characters. A string is actually an object of the C++ Standard

You can use the assignment (=) operator with

vector objects.

As with C-style pointer-based arrays, C++ does not

perform any bounds checking when vector elements

are accessed with square brackets.

Standard class template vector provides bounds

checking in its member function at

“throws an exception” (Exception Handling) if its argument

is an invalid subscript.

C++ Standard Library Class Template vector