Ch 7. Constructors and Other Tools
|
|
- Reynard Lindsey
- 6 years ago
- Views:
Transcription
1 Ch 7. Constructors and Other Tools September 3, 2013 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel : ; Fax : ytkim@yu.ac.kr)
2 Constructors Definitions Calling Outline More Tools const parameter modifier Inline functions Static member data ch 7-2
3 Initialization of objects Constructors Initialize some or all member variables Other actions possible as well A special kind of member function Automatically called when object declared Very useful tool Key principle of OOP ch 7-3
4 Constructor Definitions Constructors defined like any member function Except: 1) Must have same name as class 2) Cannot return a value; not even void! ch 7-4
5 Constructor Definition Example Class definition with constructor: class DayOfYear public: DayOfYear(int monthvalue, int dayvalue); //Constructor initializes month & day void input(); void output(); private: int month; int day; ch 7-5
6 Constructor Notes Notice name of constructor: DayOfYear Same name as class itself! Constructor declaration has no return-type Not even void! Constructor in public section It s called when objects are declared If private, could never declare objects! ch 7-6
7 Calling Constructors Declare objects: DayOfYear date1(7, 4), date2(5, 5); Objects are created here Constructor is called Values in parentheses passed as arguments to constructor Member variables month, day initialized: date1.month 7 date2.month 5 date1.dat 4 date2.day 5 ch 7-7
8 Consider: Constructor Equivalency DayOfYear date1, date2 date1.dayofyear(7, 4); // ILLEGAL! date2.dayofyear(5, 5); // ILLEGAL! Seemingly OK CANNOT call constructors like other member functions! ch 7-8
9 Constructor Code Constructor definition is like all other member functions: DayOfYear::DayOfYear(int monthvalue, int dayvalue) month = monthvalue; day = dayvalue; Note 1: same name around :: Clearly identifies a constructor Note 2: no return type Just as in class definition ch 7-9
10 Alternative Definition Previous definition equivalent to: DayOfYear::DayOfYear(int monthvalue, int dayvalue) : month(monthvalue), day(dayvalue) Third line called "Initialization Section" Body left empty Preferable definition version ch 7-10
11 Constructor Additional Purpose Not just initialize data Body doesn t have to be empty In initializer version Validate the data! Ensure only appropriate data is assigned to class private member variables Powerful OOP principle ch 7-11
12 Overloaded Constructors Can overload constructors just like other functions Recall: a signature consists of: Name of function Parameter list Provide constructors for all possible argument-lists Particularly "how many" ch 7-12
13 Class with Constructors Example ch 7-13
14 ch 7-14
15 ch 7-15
16 Constructor with No Arguments Can be confusing Standard functions with no arguments: Called with syntax: callmyfunction(); Including empty parentheses Object declarations with no "initializers": DayOfYear date1; // This way! DayOfYear date(); // NO! What is this really? Compiler sees a function declaration/prototype! Yes! Look closely! ch 7-16
17 Explicit Constructor Calls Can also call constructor AGAIN After object declared Recall: constructor was automatically called then Can call via object s name; standard member function call Convenient method of setting member variables Method quite different from standard member function call ch 7-17
18 Explicit Constructor Call Example Such a call returns "anonymous object" Which can then be assigned In Action: DayOfYear holiday(7, 4); Constructor called at object s declaration Now to "re-initialize": holiday = DayOfYear(5, 5); Explicit constructor call Returns new "anonymous object" Assigned back to current object ch 7-18
19 Default Constructor Defined as: constructor w/ no arguments One should always be defined Auto-Generated? Yes & No If no constructors AT ALL are defined Yes If any constructors are defined No If no default constructor: Cannot declare: MyClass myobject; With no initializers ch 7-19
20 Class Type Member Variables Class member variables can be any type Including objects of other classes! Type of class relationship Powerful OOP principle Need special notation for constructors So they can call "back" to member object s constructor ch 7-20
21 Class Member Variable Example: ch 7-21
22 ch 7-22
23 ch 7-23
24 ch 7-24
25 ch 7-25
26 Parameter Passing Methods Efficiency of parameter passing Call-by-value Requires copy be made Overhead Call-by-reference Placeholder for actual argument Most efficient method Negligible difference for simple types For class types clear advantage Call-by-reference desirable Especially for "large" data, like class types ch 7-26
27 The const Parameter Modifier Large data types (typically classes) Desirable to use pass-by-reference Even if function will not make modifications Protect argument Use constant parameter Also called constant call-by-reference parameter Place keyword const before type Makes parameter "read-only" Attempts to modify result in compiler error ch 7-27
28 Use of const If no need for function modifications Protect parameter with const Protect ALL such parameters void BankAccount::output() const Using const, we can also protect class member function s parameters void welcome(const BankAccount& youraccount) ch 7-28
29 // Display 7.4 The const Parameter Modifier #include <iostream> #include <cmath> #include <cstdlib> using namespace std; //Data consists of two items, an amount of money for the account balance //and a percent for the interest rate. class BankAccount public: BankAccount(double balance, double rate); //Initializes balance and rate according to arguments. BankAccount(int dollars, int cents, double rate); //Initializes the account balance to $dollars.cents. For a negative balance both //dollars and cents must be negative. Initializes the interest rate to rate percent. BankAccount(int dollars, double rate); //Initializes the account balance to $dollars.00 and //initializes the interest rate to rate percent. BankAccount( ); //Initializes the account balance to $0.00 and the interest rate to 0.0%. ch 7-29
30 void update( ); //Postcondition: One year of simple interest has been added to the account. void input( ); void output( ) const; double getbalance( ) const; int getdollars( ) const; int getcents( ) const; double getrate( ) const;//returns interest rate as a percent. void setbalance(double balance); void setbalance(int dollars, int cents); //checks that arguments are both nonnegative or both nonpositive void setrate(double newrate); //If newrate is nonnegative, it becomes the new rate. Otherwise abort program. private: //A negative amount is represented as negative dollars and negative cents. //For example, negative $4.50 sets accountdollars to -4 and accountcents to -50. int accountdollars; //of balance int accountcents; //of balance double rate; //as a percent int dollarspart(double amount) const; int centspart(double amount) const; int round(double number) const; double fraction(double percent) const; //Converts a percent to a fraction. For example, fraction(50.3) returns ; ch 7-30
31 //Returns true if the balance in account1 is greater than that //in account2. Otherwise returns false. bool islarger(const BankAccount& account1, const BankAccount& account2); void welcome(const BankAccount& youraccount); int main( ) BankAccount account1( , 4.5), account2; welcome(account1); cout << "Enter data for account 2:\ n"; account2.input( ); if (islarger(account1, account2)) cout << "account1 is larger.\ n"; else cout << "account2 is at least as large as account1.\ n"; return 0; bool islarger(const BankAccount& account1, const BankAccount& account2) return(account1.getbalance( ) > account2.getbalance( )); void welcome(const BankAccount& youraccount) cout << "Welcome to our bank.\ n" << "The status of your account is:\ n"; youraccount.output( ); ch 7-31
32 //Uses iostream and cstdlib: void BankAccount::output( ) const int absdollars = abs(accountdollars); int abscents = abs(accountcents); cout << "Account balance: $"; if (accountdollars < 0) cout << "-"; cout << absdollars; if (abscents >= 10) cout << "." << abscents << endl; else cout << "." << '0' << abscents << endl; cout << "Rate: " << rate << "%\ n"; BankAccount::BankAccount(double balance, double rate) : accountdollars(dollarspart(balance)), accountcents(centspart(balance)) setrate(rate); BankAccount::BankAccount(int dollars, int cents, double rate) setbalance(dollars, cents); setrate(rate); BankAccount::BankAccount(int dollars, double rate) : accountdollars(dollars), accountcents(0) setrate(rate); ch 7-32
33 BankAccount::BankAccount( ): accountdollars(0), accountcents(0), rate(0.0) /*Body intentionally empty.*/ void BankAccount::update( ) double balance = accountdollars + accountcents*0.01; balance = balance + fraction(rate)*balance; accountdollars = dollarspart(balance); accountcents = centspart(balance); //Uses iostream: void BankAccount::input( ) double balanceasdouble; cout << "Enter account balance $"; cin >> balanceasdouble; accountdollars = dollarspart(balanceasdouble); accountcents = centspart(balanceasdouble); cout << "Enter interest rate (NO percent sign): "; cin >> rate; setrate(rate); double BankAccount::getBalance( ) const return (accountdollars + accountcents*0.01); int BankAccount::getDollars( ) const return accountdollars; ch 7-33
34 int BankAccount::getCents( ) const return accountcents; void BankAccount::setBalance(double balance) accountdollars = dollarspart(balance); accountcents = centspart(balance); //Uses cstdlib: void BankAccount::setBalance(int dollars, int cents) if ((dollars < 0 && cents > 0) (dollars > 0 && cents < 0)) cout << "Inconsistent account data.\ n"; exit(1); accountdollars = dollars; accountcents = cents; double BankAccount::getRate( ) const return rate; //Uses cstdlib: void BankAccount::setRate(double newrate) if (newrate >= 0.0) rate = newrate; else cout << "Cannot have a negative interest rate.\ n"; exit(1); ch 7-34
35 int BankAccount::dollarsPart(double amount) const return static_cast<int>(amount); //Uses cmath: int BankAccount::centsPart(double amount) const double doublecents = amount*100; int intcents = (round(fabs(doublecents)))%100;//% can misbehave on negatives if (amount < 0) intcents = -intcents; return intcents; //Uses cmath: int BankAccount::round(double number) const return floor(number + 0.5); double BankAccount::fraction(double percent) const return (percent/100.0); ch 7-35
36 Inline Functions For non-member functions: Use keyword inline in function declaration and function heading For class member functions: Place implementation (code) for function IN class definition automatically inline class BankAccount public:... double getbalance() const return (accountdollars + accountcents*0.01); int getdollars() cost return accountdollars;... private: int accountdollars; int accountcents;... ch 7-36
37 Inline Member Functions Member function definitions Typically defined separately, in different file Can be defined IN class definition Makes function "in-line" Code actually inserted in place of call Eliminates overhead More efficient, but only when short! Use for very short functions only More efficient If too long actually less efficient! ch 7-37
38 Static Members Static member variables All objects of class "share" one copy One object changes it all see change Useful for "tracking" How often a member function is called How many objects exist at given time Place keyword static before type ch 7-38
39 Static Functions Member functions can be static If no access to object data needed And still "must" be member of the class Make it a static function Can then be called outside class From non-class objects: E.g., Server::getTurn(); As well as via class objects Standard method: myobject.getturn(); Can only use static data, functions! ch 7-39
40 Static Members Example ch 7-40
41 ch 7-41
42 ch 7-42
43 ch 7-43
44 Summary 7-1 Constructors: automatic initialization of class data Called when objects are declared Constructor has same name as class Default constructor has no parameters Should always be defined Class member variables Can be objects of other classes Require initialization-section ch 7-44
45 Summary 7-2 Constant call-by-reference parameters More efficient than call-by-value Can inline very short function definitions Can improve efficiency Static member variables Shared by all objects of a class ch 7-45
46 Homework Program C++ class for matrix (1) Write a header file Class_Mtrx.h with a class Mtrx with following members: /* Class_Mtrx.h */ class Mtrx public: Mtrx(int msize); Mtrx(double da[], int num_data, int msize); void print(); Mtrx add(mtrx); Mtrx multiply(mtrx); private: int msize; double **dm; double det; ; ch 7-46
47 (2) Write a C++ mtrx.cpp that implements the member functions: (1) Mtrx(int msize); - constructor that dynamically creates two dimensional array for the data member dm[msize][msize], and initialize the dm[][] with initial values of 0.0 (2) Mtrx(double da[], int msize); - constructor that receives an array da[msize * msize], and dynamically creates two dimensional array for the data member dm[msize][msize], and initialize the dm[][] with the given data (3) void print(); - prints out the dm[][] (4) Mtrx add(mtrx ma); - creates a Mtrx mr and calculates the addition of mr.dm[][] = this.dm[][] + ma.dm[][], and returns the mr (5) Mtrx multiply(mtrx); - creates a Mtrx mr and calculates the addition of mr.dm[][] = this.dm[][] x ma.dm[][], and returns the mr ch 7-47
48 (3) Use following main() function, and produce the results. /* main.cpp */ #define SIZE_N 5 void main() double ma[size_n*size_n] = 1.0, 2.0, 3.0, 4.0, 5.0, 2.0, 3.0, 4.0, 5.0, 1.0, 3.0, 2.0, 5.0, 3.0, 2.0, 4.0, 3.0, 2.0, 7.0, 2.0, 5.0, 4.0, 3.0, 2.0, 9.0 ; double mb[size_n*size_n] = 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 ; Mtrx mtrxa(ma, SIZE_N*SIZE_N, SIZE_N); cout <<"MtrxA:\ n"; mtrxa.print(); Mtrx mtrxb(mb, SIZE_N*SIZE_N, SIZE_N); cout <<"MtrxB:\ n"; mtrxb.print(); ch 7-48
49 Mtrx mtrxc(size_n); cout <<"MtrxC:\ n"; mtrxc.print(); mtrxc = mtrxa.add(mtrxb); cout <<"MtrxC = mtrxa.addmtrx(mtrxb) :\ n"; mtrxc.print(); Mtrx mtrxd(size_n); mtrxd = mtrxa.multiply(mtrxb); cout <<"MtrxD = mtrxa.multiply(mtrxb) :\ n"; mtrxd.print(); // end main() ch 7-49
50 7.2 Programming projects 7-8. (histogram of grades) ch 7-50
Chapter 7 Constructors and Other Tools. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo
Chapter 7 Constructors and Other Tools 1 Learning Objectives Constructors Definitions Calling More Tools const parameter modifier Inline functions Static member data Vectors Introduction to vector class
More informationChapter 7. Constructors and Other Tools. Copyright 2016 Pearson, Inc. All rights reserved.
Chapter 7 Constructors and Other Tools Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives Constructors Definitions Calling More Tools const parameter modifier Inline functions Static
More informationCh 8. Operator Overloading, Friends, and References
2014-1 Ch 8. Operator Overloading, Friends, and References May 28, 2014 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel
More informationStarting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,
Classes Starting Savitch Chapter 10 l l A class is a data type whose variables are objects Some pre-defined classes in C++ include int, char, ifstream Of course, you can define your own classes too A class
More informationCh 6. Structures and Classes
2013-2 Ch 6. Structures and Classes September 1, 2013 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel : +82-53-810-2497;
More informationChapter 10 Defining Classes
Chapter 10 Defining Classes What Is a Class? A class is a data type whose variables are objects Some pre-defined data types you have used are int char You can define your own classes define your own types
More informationSimplest version of DayOfYear
Reminder from last week: Simplest version of DayOfYear class DayOfYear { public: void output(); int month; int day; }; Like a struct with an added method All parts public Clients access month, day directly
More informationChapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved
Chapter 8 Operator Overloading, Friends, and References Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives Basic Operator Overloading Unary operators As member functions Friends
More informationCh 4. Parameters and Function Overloading
2014-1 Ch 4. Parameters and Function Overloading March 19, 2014 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel : +82-53-810-2497;
More informationRoxana Dumitrescu. C++ in Financial Mathematics
Roxana Dumitrescu C++ in Financial Mathematics What have we learnt? Arrays; relation between arrays and pointers.. Returning arrays from functions Passing arrays to functions Intoduction to classes Plan
More informationCh 6-1. Structures. March 30, Prof. Young-Tak Kim
2014-1 Ch 6-1. Structures March 30, 2014 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel : +82-53-810-2497; Fax : +82-53-810-4742
More informationAN OVERVIEW OF C++ 1
AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function
More informationProgramming Language. Functions. Eng. Anis Nazer First Semester
Programming Language Functions Eng. Anis Nazer First Semester 2016-2017 Definitions Function : a set of statements that are written once, and can be executed upon request Functions are separate entities
More informationUsing the Xcode Debugger
g Using the Xcode Debugger J Objectives In this appendix you ll: Set breakpoints and run a program in the debugger. Use the Continue program execution command to continue execution. Use the Auto window
More informationCh 5-2. Arrays Part 2
2014-1 Ch 5-2. Arrays Part 2 March 29, 2014 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel : +82-53-810-2497; Fax : +82-53-810-4742
More informationLinked List using a Sentinel
Linked List using a Sentinel Linked List.h / Linked List.h Using a sentinel for search Created by Enoch Hwang on 2/1/10. Copyright 2010 La Sierra University. All rights reserved. / #include
More informationSoftware Design and Analysis for Engineers
Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 2 Date:
More informationCISC 2200 Data Structure Fall, C++ Review:3/3. 1 From last lecture:
CISC 2200 Data Structure Fall, 2016 C++ Review:3/3 1 From last lecture: pointer type and pointer variable (stores memory addresses of a variable (of any type, local or global, automatic/static/dynamic)
More informationIntroduction to C++ Systems Programming
Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions
More informationLecture 7. Log into Linux New documents posted to course webpage
Lecture 7 Log into Linux New documents posted to course webpage Coding style guideline; part of project grade is following this Homework 4, due on Monday; this is a written assignment Project 1, due next
More informationAbstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles
Abstract Data Types (ADTs) CS 247: Software Engineering Principles ADT Design An abstract data type (ADT) is a user-defined type that bundles together: the range of values that variables of that type can
More informationDataStruct 9. Hash Tables, Maps, Skip Lists, and Dictionaries
2013-2 DataStruct 9. Hash Tables, Maps, Skip Lists, and Dictionaries Michael T. Goodrich, et. al, Data Structures and Algorithms in C++, 2 nd Ed., John Wiley & Sons, Inc., 2011. November 22, 2013 Advanced
More informationIII. Classes (Chap. 3)
III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,
More informationWelcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:
Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams
More informationCS 247: Software Engineering Principles. ADT Design
CS 247: Software Engineering Principles ADT Design Readings: Eckel, Vol. 1 Ch. 7 Function Overloading & Default Arguments Ch. 12 Operator Overloading U Waterloo CS247 (Spring 2017) p.1/17 Abstract Data
More informationC++ For Science and Engineering Lecture 12
C++ For Science and Engineering Lecture 12 John Chrispell Tulane University Monday September 20, 2010 Comparing C-Style strings Note the following listing dosn t do what you probably think it does (assuming
More informationC++ basics Getting started with, and Data Types.
C++ basics Getting started with, and Data Types pm_jat@daiict.ac.in Recap Last Lecture We talked about Variables - Variables, their binding to type, storage etc., Categorization based on storage binding
More informationImperative Languages!
Imperative Languages! Java is an imperative object-oriented language. What is the difference in the organisation of a program in a procedural and an objectoriented language? 30 class BankAccount { private
More informationCHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Program Components in C++ 3. Math Library Functions 4. Functions 5. Function Definitions 6. Function Prototypes 7. Header Files 8.
More informationPIC 10A. Lecture 15: User Defined Classes
PIC 10A Lecture 15: User Defined Classes Intro to classes We have already had some practice with classes. Employee Time Point Line Recall that a class is like a souped up variable that can store data,
More informationFriends and Overloaded Operators
Friend Function Friends and Overloaded Operators Class operations are typically implemented as member functions Some operations are better implemented as ordinary (nonmember) functions CSC 330 OO Software
More informationFriends and Overloaded Operators
Friends and Overloaded Operators Friend Function Class operations are typically implemented as member functions Some operations are better implemented as ordinary (nonmember) functions CSC 330 OO Software
More informationFunctions. CS111 Lab Queens College, CUNY Instructor: Kent Chin
Functions CS111 Lab Queens College, CUNY Instructor: Kent Chin Functions They're everywhere! Input: x Function: f Output: f(x) Input: Sheets of Paper Function: Staple Output: Stapled Sheets of Paper C++
More informationDiscussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:
Discussion 1H Notes (Week 3, April 14) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 More on Arithmetic Expressions The following two are equivalent:! x = x + 5;
More informationDue Date: See Blackboard
Source File: ~/2315/45/lab45.(C CPP cpp c++ cc cxx cp) Input: under control of main function Output: under control of main function Value: 4 Integer data is usually represented in a single word on a computer.
More informationCh 6-8. C-Strings. April 30, Prof. Young-Tak Kim
2014-1 Ch 6-8. C-Strings April 30, 2014 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel : +82-53-810-2497; Fax : +82-53-810-4742
More informationWelcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:
Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams
More informationLab Instructor : Jean Lai
Lab Instructor : Jean Lai Group related statements to perform a specific task. Structure the program (No duplicate codes!) Must be declared before used. Can be invoked (called) as any number of times.
More informationReview: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements
Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja
More informationFundamentals of Programming. Lecture 19 Hamed Rasifard
Fundamentals of Programming Lecture 19 Hamed Rasifard 1 Outline C++ Object-Oriented Programming Class 2 C++ C++ began as an expanded version of C. C++ improves on many of C s features and provides object-oriented-programming
More informationCpt S 122 Data Structures. Introduction to C++ Part II
Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function
More informationModern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi
Modern C++ for Computer Vision and Image Processing Igor Bogoslavskyi Outline Move semantics Classes Operator overloading Making your class copyable Making your class movable Rule of all or nothing Inheritance
More informationChapter 3 Function Basics
Chapter 3 Function Basics Learning Objectives Predefined Functions Those that return a value and those that don t Programmer-defined Functions Defining, Declaring, Calling Recursive Functions Scope Rules
More informationThe American University in Cairo Department of Computer Science & Engineeringt CSCI &09 Dr. KHALIL Exam-I Fall 2009
The American University in Cairo Department of Computer Science & Engineeringt CSCI 106-05&09 Dr. KHALIL Exam-I Fall 2009 Last Name :... ID:... First Name:... Form I Section No.: EXAMINATION INSTRUCTIONS
More informationC++_ MARKS 40 MIN
C++_16.9.2018 40 MARKS 40 MIN https://tinyurl.com/ya62ayzs 1) Declaration of a pointer more than once may cause A. Error B. Abort C. Trap D. Null 2Whice is not a correct variable type in C++? A. float
More informationProgramming Abstractions
Programming Abstractions C S 1 0 6 B Cynthia Lee Topics du Jour: Make your own classes! Needed for Boggle assignment! We are starting to see a little bit in MarbleBoard assignment as well 2 Classes in
More informationIntroduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.
Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and
More informationBasic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces
Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program
More informationChapter 15 - C++ As A "Better C"
Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference
More informationOutline. Why do we write functions? Introduction to Functions. How do we write functions? Using Functions. Introduction to Functions March 21, 2006
Introduction to User-defined Functions Larry Caretto Computer Science 106 Computing in Engineering and Science March 21, 2006 Outline Why we use functions Writing and calling a function Header and body
More informationAbsolute C++ Walter Savitch
Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents
More informationVariables. Data Types.
Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting
More informationStructures and Classes CS 16: Solving Problems with Computers I Lecture #15
Structures and Classes CS 16: Solving Problems with Computers I Lecture #15 Ziad Matni Dept. of Computer Science, UCSB WHAT THE NEXT 3 WEEKS LOOK LIKE MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY 20- Nov 21-
More informationReview: C++ Basic Concepts. Dr. Yingwu Zhu
Review: C++ Basic Concepts Dr. Yingwu Zhu Outline C++ class declaration Constructor Overloading functions Overloading operators Destructor Redundant declaration A Real-World Example Question #1: How to
More informationCS 117 Programming II, Spring 2018 Dr. Ghriga. Midterm Exam Estimated Time: 2 hours. March 21, DUE DATE: March 28, 2018 at 12:00 PM
CS 117 Programming II, Spring 2018 Dr. Ghriga Midterm Exam Estimated Time: 2 hours March 21, 2018 DUE DATE: March 28, 2018 at 12:00 PM INSTRUCTIONS: Do all exercises for a total of 100 points. You are
More informationSOLUTIONS TO EXERCISES PART ONE: Problem-Solving Techniques
SOLUTIONS TO EXERCISES PART ONE: Problem-Solving Techniques 1 Principles of Programming and Software Engineering 1 const CENTS_PER_DOLLAR = 100; void computechange(int dollarcost, int centscost, int& d,
More informationConstructors.
Constructors Initializing New Objects Fraction g(4, 5); Initializing New Objects Fraction g(4, 5); Initializing New Objects Fraction g(4, 5); Initializing New Objects Fraction g(4, 5); Initializing New
More informationExceptions, Case Study-Exception handling in C++.
PART III: Structuring of Computations- Structuring the computation, Expressions and statements, Conditional execution and iteration, Routines, Style issues: side effects and aliasing, Exceptions, Case
More informationGE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004
GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004 Functions and Program Structure Today we will be learning about functions. You should already have an idea of their uses. Cout
More informationIntroduction to Programming
Introduction to Programming session 6 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Spring 2011 These slides are created using Deitel s slides Sharif University of Technology Outlines
More informationIntroduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts
Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter
More informationLecture 3 ADT and C++ Classes (II)
CSC212 Data Structure - Section FG Lecture 3 ADT and C++ Classes (II) Instructor: Feng HU Department of Computer Science City College of New York @ Feng HU, 2016 1 Outline A Review of C++ Classes (Lecture
More informationMore class design with C++ Starting Savitch Chap. 11
More class design with C++ Starting Savitch Chap. 11 Member or non-member function? l Class operations are typically implemented as member functions Declared inside class definition Can directly access
More informationObject Oriented Design
Object Oriented Design Chapter 6 Example Activity Diagram 1 Outline Chapter 6 Topics 6.6 C++ Standard Library Header Files 6.14 Inline Functions 6.16 Default Arguments 6.17 Unary Scope Resolution Operator
More informationC++ Programming Fundamentals
C++ Programming Fundamentals 269 Elvis C. Foster Lecture 11: Templates One of the contemporary sophistries of C++ programming is defining and manipulating templates. This lecture focuses on this topic.
More informationCh 1. Algorithms and Basic C++ Programming
2013-2 Ch 1. Algorithms and Basic C++ Programming July 1, 2013 Dept. of Information & Communication Engineering College of Engineering Yeungnam University, KOREA (Tel : +82-53-810-2497; Fax : +82-53-810-4742
More informationCSCE 206: Structured Programming in C++
CSCE 206: Structured Programming in C++ 2017 Spring Exam 2 Monday, March 20, 2017 Total - 100 Points B Instructions: Total of 13 pages, including this cover and the last page. Before starting the exam,
More informationMultiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)
Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program
More informationObject-Oriented Programming in C++
Object-Oriented Programming in C++ Pre-Lecture 9: Advanced topics Prof Niels Walet (Niels.Walet@manchester.ac.uk) Room 7.07, Schuster Building March 24, 2015 Prelecture 9 Outline This prelecture largely
More informationCS
CS 1666 www.cs.pitt.edu/~nlf4/cs1666/ Programming in C++ First, some praise for C++ "It certainly has its good points. But by and large I think it s a bad language. It does a lot of things half well and
More informationFunction Call Example
Function Call Example A Function Call Example (1) ch 3-25 A Function Call Example (2) ch 3-26 Alternative Function Declaration Recall: Function declaration is "information for compiler Compiler only needs
More informationCh 6. Functions. Example: function calls function
Ch 6. Functions Part 2 CS 1428 Fall 2011 Jill Seaman Lecture 21 1 Example: function calls function void deeper() { cout
More informationCHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad
CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING Dr. Shady Yehia Elmashad Outline 1. Introduction to C++ Programming 2. Comment 3. Variables and Constants 4. Basic C++ Data Types 5. Simple Program: Printing
More informationProblem Solving with C++
GLOBAL EDITION Problem Solving with C++ NINTH EDITION Walter Savitch Kendrick Mock Ninth Edition PROBLEM SOLVING with C++ Problem Solving with C++, Global Edition Cover Title Copyright Contents Chapter
More informationFast Introduction to Object Oriented Programming and C++
Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming
More informationProgramming in C++: Assignment Week 8
Programming in C++: Assignment Week 8 Total Marks : 20 September 9, 2017 Question 1 Consider the following code segment. Mark 2 void myfunction(int test) { try { if (test) throw test; else throw "Value
More informationCIS 190: C/C++ Programming. Classes in C++
CIS 190: C/C++ Programming Classes in C++ Outline Header Protection Functions in C++ Procedural Programming vs OOP Classes Access Constructors Headers in C++ done same way as in C including user.h files:
More informationObject-Oriented Programming for Scientific Computing
Object-Oriented Programming for Scientific Computing Dynamic Memory Management Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 2. Mai 2017
More informationPIC 10A. Final Review: Part I
PIC 10A Final Review: Part I Final exam The final exam is worth 30% of your grade, same weight as 2 midterms. Could be 50% if grading option 2 turns out better for you. Length is also roughly 2 midterms
More informationFunctions that Return a Value. Approximate completion time Pre-lab Reading Assignment 20 min. 92
L E S S O N S E T 6.2 Functions that Return a Value PURPOSE PROCEDURE 1. To introduce the concept of scope 2. To understand the difference between static, local and global variables 3. To introduce the
More informationSFU CMPT Topic: Classes
SFU CMPT-212 2008-1 1 Topic: Classes SFU CMPT-212 2008-1 Topic: Classes Ján Maňuch E-mail: jmanuch@sfu.ca Friday 15 th February, 2008 SFU CMPT-212 2008-1 2 Topic: Classes Encapsulation Using global variables
More informationMultiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)
Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program
More informationCOEN244: Class & function templates
COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library
More informationCSCE 110 PROGRAMMING FUNDAMENTALS
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class Prof. amr Goneid, AUC 1 Dictionaries(1): A Key Table Class Prof. Amr Goneid, AUC 2 A Key Table
More informationMultiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)
Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program
More informationIslamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.
Islamic University of Gaza Computer Engineering Dept. C++ Programming For Industrial And Electrical Engineering By Instructor: Ruba A. Salamh Chapter Four: Loops 2 Chapter Goals To implement while, for
More informationCPSC 427: Object-Oriented Programming
CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 7 September 21, 2016 CPSC 427, Lecture 7 1/21 Brackets Example (continued) Storage Management CPSC 427, Lecture 7 2/21 Brackets Example
More informationUnit 7. 'while' Loops
1 Unit 7 'while' Loops 2 Control Structures We need ways of making decisions in our program To repeat code until we want it to stop To only execute certain code if a condition is true To execute one segment
More informationPIC 10A. Lecture 17: Classes III, overloading
PIC 10A Lecture 17: Classes III, overloading Function overloading Having multiple constructors with same name is example of something called function overloading. You are allowed to have functions with
More informationOperator overloading: extra examples
Operator overloading: extra examples CS319: Scientific Computing (with C++) Niall Madden Week 8: some extra examples, to supplement what was covered in class 1 Eg 1: Points in the (x, y)-plane Overloading
More informationCIS 130 Exam #2 Review Suggestions
CIS 130 - Exam #2 Review Suggestions p. 1 * last modified: 11-11-05, 12:32 am CIS 130 Exam #2 Review Suggestions * remember: YOU ARE RESPONSIBLE for course reading, lectures/labs, and especially anything
More informationObject oriented programming
Exercises 7 Version 1.0, 11 April, 2017 Table of Contents 1. Inheritance.................................................................. 1 1.1. Tennis Player...........................................................
More informationCSE143 Exam with answers MIDTERM #1, 1/26/2001 Problem numbering may differ from the test as given.
CSE143 Exam with answers MIDTERM #1, 1/26/2001 Problem numbering may differ from the test as given. All multiple choice questions are equally weighted. You can generally assume that code shown in the questions
More informationLab 2: ADT Design & Implementation
Lab 2: ADT Design & Implementation By Dr. Yingwu Zhu, Seattle University 1. Goals In this lab, you are required to use a dynamic array to design and implement an ADT SortedList that maintains a sorted
More informationGovernment Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING
Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING THROUGH C++ Practical: OOPS THROUGH C++ Subject Code: 1618407 PROGRAM NO.1 Programming exercise on executing a Basic C++
More informationWhy Is Repetition Needed?
Why Is Repetition Needed? Repetition allows efficient use of variables. It lets you process many values using a small number of variables. For example, to add five numbers: Inefficient way: Declare a variable
More informationNote 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...
CISC 2000 Computer Science II Fall, 2014 Note 12/1/2014 1 Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... (a) What s the purpose of inheritance?
More informationModule 7 b. -Namespaces -Exceptions handling
Module 7 b -Namespaces -Exceptions handling C++ Namespace Often, a solution to a problem will have groups of related classes and other declarations, such as functions, types, and constants. C++provides
More informationOverloading Operators in C++
Overloading Operators in C++ C++ allows the programmer to redefine the function of most built-in operators on a class-by-class basis the operator keyword is used to declare a function that specifies what
More informationBruce Merry. IOI Training Dec 2013
IOI Training Dec 2013 Outline 1 2 3 Outline 1 2 3 You can check that something is true using assert: #include int main() { assert(1 == 2); } Output: test_assert: test_assert.cpp:4: int main():
More information