February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 1 The vector Container Type When a vector is created, its elements are initialized.

Slides:



Advertisements
Similar presentations
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Advertisements

Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Kernighan/Ritchie: Kelley/Pohl:
Chapter 14: Overloading and Templates
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
Guide To UNIX Using Linux Third Edition
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Review of C++ Programming Part II Sheng-Fang Huang.
CS 192 Lecture 3 Winter 2003 December 5, 2003 Dr. Shafay Shamail.
COMPUTER PROGRAMMING. Data Types “Hello world” program Does it do a useful work? Writing several lines of code. Compiling the program. Executing the program.
C++ for Engineers and Scientists Third Edition
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
C++ for Engineers and Scientists Second Edition Chapter 6 Modularity Using Functions.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Introduction to C++ Systems Programming. Systems Programming: Introduction to C++ 2 Systems Programming: 2 Introduction to C++  Syntax differences between.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Functions Kernighan/Ritchie: Kelley/Pohl: Chapter 4 Chapter 5.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
1 C++ Syntax and Semantics, and the Program Development Process.
Learners Support Publications Classes and Objects.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
FUNCTIONS. Funtions  The heart of effective problem solving is problem decomposition.  breaking a problem into small, manageable pieces  In C, the.
#include using namespace std; // Declare a function. void check(int, double, double); int main() { check(1, 2.3, 4.56); check(7, 8.9, 10.11); } void check(int.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
Object-Oriented Programming (OOP) and C++
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Chapter 6 Modularity Using Functions
C++ Lesson 1.
Eine By: Avinash Reddy 09/29/2016.
User-Written Functions
Chapter 7: User-Defined Functions II
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Boston High School Education Project
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Introduction to C++ Systems Programming.
A Lecture for the c++ Course
Classes and Objects.
Submitted By : Veenu Saini Lecturer (IT)
The vector Container Type
CS410 – Software Engineering Lecture #3: C++ Basics I
Presentation transcript:

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 1 The vector Container Type When a vector is created, its elements are initialized with the default value for their type. However, we can specify a different value. Example: vector charVec(10, ‘x’); initializes all ten elements of charVec with the value ‘x’. (By the way, the default value for characters is the blank character or space.)

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 2 The vector Container Type A vector can also be initialized by specifying the first and one past the last element of an existing array. Example: int intArray[8] = {10, 20, 30, 40, 50, 60, 70, 80}; vector intVec(intArray + 1, intArray + 5); creates a vector of size four with elements 20, 30, 40, and 50. A vector can also be initialized with or assigned to another vector.

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 3 The vector Container Type The STL idiom is quite different from the array idiom. We start with defining an empty vector, for example: vector dblVec; Then we can add items to the back of the vector (and thereby expanding the vector) using the push_back operation: dblVec.push_back(3.7);dblVec.push_back(2.2);dblVec.push_back(-5.1); results in vector of size 3 with elements 3.7, 2.2, -5.1.

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 4 The pair Type Another class in the standard library that uses the template facility is the pair class. It allows us to combine two values of either the same or different types within a single object. If we want to use pairs, we must include the following header file: #include #include Then we can start defining pairs such as: pair FranksData(“Frank Miller”, 4.0);

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 5 The pair Type We use member access notation to access the individual members of a pair: string name = FranksData.first; double GPA = FranksData.second; We can manipulate the values of the members analogously: FranksData.second = 1.0;

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 6 Typedef Names For pair objects, it is often helpful to use the typedef mechanism. This mechanism allows us to define mnemonic synonyms for built-in and user-defined data types. Example: typedef pair studentGPA; studentGPA frank(“Frank Miller”, 4.0); studentGPA doris(“Doris Carpenter”, 3.5); studentGPA jeff(“Jeff Bridges”, 2.47);

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 7 Typedef Names Typedef names can improve the readability of our programs.Typedef names can improve the readability of our programs. Notice that typedef names do not introduce new types but only synonyms for existing data types.Notice that typedef names do not introduce new types but only synonyms for existing data types. For example, the following code is correct: typedef double GPA; GPA JohnsGPA = 3.4; double BobsGPA; BobsGPA = JohnsGPA;

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 8 Class Types In C++, classes are defined as follows: class Classname {public: // public member variables and member functions // public member variables and member functions …private: // private member variables and member functions // private member variables and member functions …protected: // protected member variables and member functions // protected member variables and member functions …};

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 9 Class Types Public members are accessible from anywhere within the program. To achieve information hiding, you should generally limit the public members of a class to a small set of member functions that allow the manipulation of the class objects. Private members can be accessed only by the member functions and friends of its class. For information hiding, you should declare all member variables (data members) as private. Protected members behave as public members to a derived class and as private members to the rest of the program.

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 10 Class Types The declaration of class data members is identical to the declaration of variables. Member functions are usually declared within the class definition and defined outside of it. Notice that when you define member functions outside the class definition, you have to provide the class name and the scope resolution operator (::).

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 11 Class Types class StudentAdmonisher {public: bool SetRobotState(robotState); bool SetRobotState(robotState); robotState GetRobotState(); robotState GetRobotState();private: robotState currentState; robotState currentState;}; bool StudentAdmonisher::SetRobotState(robotState rs) { currentState = rs; return true; } robotState StudentAdmonisher::GetRobotState() { return currentState; }

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 12 Class Types However, short member functions can also be placed inside the class body. Example: class StudentAdmonisher {public: bool SetRobotState(robotState rs) { currentState = rs; return true }; bool SetRobotState(robotState rs) { currentState = rs; return true }; robotState GetRobotState() { return currentState }; robotState GetRobotState() { return currentState };private: robotState currentState; robotState currentState;};

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 13Functions Function definition and declaration Function definition and declaration Default arguments Default arguments Functions as arguments Functions as arguments Overloading functions Overloading functions Inlining Inlining Storage classes Storage classes

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 14 Function Definition and Declaration The C++ code that describes what a function does is called the function definition. Its form is: type FunctionName(parameter-declaration-list) { statements statements}

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 15 Function Definition and Declaration A function can be declared before it is defined. It can be defined later in the file or can come from a library or a user-specified file. Such a declaration is called a function prototype and has the following general form: type FunctionName(argument-declaration-list);

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 16 Default Arguments A formal parameter can be given a default argument. A formal parameter can be given a default argument. Usually, a default argument is a constant that occurs frequently when the function is called. Usually, a default argument is a constant that occurs frequently when the function is called. Using a default argument saves writing this default value at each invocation. Using a default argument saves writing this default value at each invocation.

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 17 Default Arguments Example: int SqrOrPower(int n, int k = 2) // k = 2 is default. { assert(k > 1); // This function only works for // exponents > 1. assert(k > 1); // This function only works for // exponents > 1. if (k == 2) if (k == 2) return (n * n); return (n * n); else else return (SqrOrPower(n, k – 1) * n); return (SqrOrPower(n, k – 1) * n);} SqrOrPower(i + 5) // computes (i + 5) * (i + 5) SqrOrPower(i + 5, 3) // computes (i + 5) cubed

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 18 Default Arguments Notice that only trailing parameters of a function can have default values. This rule allows the compiler to know which arguments are defaulted when the function is called with fewer than its complete set of arguments. This rule allows the compiler to know which arguments are defaulted when the function is called with fewer than its complete set of arguments.Examples: void F1(int i, int j = 7); legal void F2(int i = 3, int j); illegal void F3(int i, int j = 3, int k = 7); legal void F4(int i = 1, int j = 2, int k = 3); legal void F5(int i, int j = 2, int k); illegal

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 19 Functions as Arguments Functions in C++ can be thought of as the addresses of the compiled code residing in memory. Functions in C++ can be thought of as the addresses of the compiled code residing in memory. Functions are therefore a form of pointer. Functions are therefore a form of pointer. Functions can be passed as a pointer-value argument into another function. Functions can be passed as a pointer-value argument into another function.

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 20 Functions as Arguments double F(double x) { return (x*x + 1.0/x); return (x*x + 1.0/x);} void plot(double Fcn(double), double x0, double incr, int n) { for (int i = 0; i < n; i++) for (int i = 0; i < n; i++) { cout << “x: “ << x0 << “ f(x): “ << Fcn(x0) << endl; cout << “x: “ << x0 << “ f(x): “ << Fcn(x0) << endl; x0 += incr; x0 += incr; }} int main() { plot(F, 0.01, 0.01, 100); plot(F, 0.01, 0.01, 100); return 0; return 0;}

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 21 Overloading Functions Overloading refers to using the same name for multiple meanings of an operator or a function. Overloading refers to using the same name for multiple meanings of an operator or a function.Example: double Average(const int a[], int size) { int sum = 0; int sum = 0; for (int i = 0; i < size; ++i) for (int i = 0; i < size; ++i) sum += a[i]; sum += a[i]; return static_cast return static_cast (sum) / size; (sum) / size;} double Average(const double a[], int size) { double sum = 0.0; double sum = 0.0; for (int i = 0; i < size; ++i) for (int i = 0; i < size; ++i) sum += a[i]; sum += a[i]; return (sum / size); return (sum / size);}

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 22 Overloading Functions The following code shows how Average() is invoked: int main() { int a[5] = {1, 2, 3, 4, 5}; int a[5] = {1, 2, 3, 4, 5}; double b[5] = {1.1, 2.2, 3.3, 4.4, 5.5}; double b[5] = {1.1, 2.2, 3.3, 4.4, 5.5}; cout << Average(a, 5) << “ int average” << endl; cout << Average(a, 5) << “ int average” << endl; cout << Average(b, 5) << “ double average” << endl; cout << Average(b, 5) << “ double average” << endl; return 0; return 0;} 3 int average 3.3 double average

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 23Inlining C++ provides the keyword inline to preface a function declaration. C++ provides the keyword inline to preface a function declaration. For functions declared as inline, the compiler will generate inline code instead of function calls. For functions declared as inline, the compiler will generate inline code instead of function calls. Inline functions lead to increased time efficiency and decreased memory efficiency. Inline functions lead to increased time efficiency and decreased memory efficiency. Question: How about recursive functions? Answer: There are no recursive inline functions because they would require infinite memory.

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 24Inlining Inlining has a similar effect as macro expansion: Inlining example: inline double cube(double x) { return (x * x * x); return (x * x * x);} Macro example: #define CUBE(X) ((X)*(X)*(X))

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 25Inlining So what is the difference between inlining and macro expansion? Answer: Macro expansion provides no type safety as is given by the C++ parameter-passing mechanism. Therefore, it is advisable to use inlining instead of macro expansion.

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 26 Storage Classes Every variable and function in the C++ kernel language has two attributes: type and storage class. Every variable and function in the C++ kernel language has two attributes: type and storage class. The four storage classes are automatic, external, register, and static. The four storage classes are automatic, external, register, and static. Variables are assigned a storage class by placing the corresponding keyword before the type specifier. Variables are assigned a storage class by placing the corresponding keyword before the type specifier.Examples: auto int a, b, c; extern float f = 7.22;

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 27 The Storage Class auto Variables declared within function blocks are by default automatic.Variables declared within function blocks are by default automatic. Therefore, automatic is the most common of the four storage classes.Therefore, automatic is the most common of the four storage classes. Automatic variables can be acted on within the scope of the enclosing block.Automatic variables can be acted on within the scope of the enclosing block.

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 28 The Storage Class extern If we want to transmit information across blocks and functions, we can use external variables.If we want to transmit information across blocks and functions, we can use external variables. When a variable is declared outside a function at the file level, storage is assigned to it permanently, and its storage class keyword is extern.When a variable is declared outside a function at the file level, storage is assigned to it permanently, and its storage class keyword is extern. Such a variable is considered to be global to all functions declared after it.Such a variable is considered to be global to all functions declared after it. The keyword extern is used to tell the compiler, “Look for it elsewhere, either in this file or in another one.”The keyword extern is used to tell the compiler, “Look for it elsewhere, either in this file or in another one.”

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 29 The Storage Class register The storage class register tells the compiler that the associated variable should be stored in high-speed memory registers.The storage class register tells the compiler that the associated variable should be stored in high-speed memory registers. This is not always possible.This is not always possible. Increases time efficiency of manipulating this variable.Increases time efficiency of manipulating this variable. Optimizing compilers assign register storage classes by themselves.Optimizing compilers assign register storage classes by themselves.

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 30 The Storage Class static Static variables retain their previous value when their block is re-entered.Static variables retain their previous value when their block is re-entered. Static functions are visible only within the file in which they are defined.Static functions are visible only within the file in which they are defined. Therefore, the static storage class provides a privacy mechanism that is very important for program modularity.Therefore, the static storage class provides a privacy mechanism that is very important for program modularity.

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 31 Assignment 2 Write a C++ program that helps UMass faculty maintain a simple student database. The program is supposed to provide the following functions: read/write database read/write database add/remove student (identified by Student ID) add/remove student (identified by Student ID) add/modify data on a student - full name - Student ID - year (freshman, sophomore, junior, or senior) add/modify data on a student - full name - Student ID - year (freshman, sophomore, junior, or senior) print the names and IDs of all freshmen, sophomores, juniors, or seniors. print the names and IDs of all freshmen, sophomores, juniors, or seniors. print all data on a student (identified by Student ID) print all data on a student (identified by Student ID) Use only the header files iostream, fstream, string and/or vector and write every line of code yourself.

February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 32 Assignment 2 Your application should simply use the terminal for input and output. Put your code into your CS410 directory. You do not need to submit a memo if you comment your code and give appropriate names to the variables in your program. Deadline is Tuesday, March 11, at 5:30pm.