Fundamentals of Programming Session 24

Similar documents
Classes: A Deeper Look

More C++ Classes. Systems Programming

Introduction to Programming session 24

Chapter 6: Classes and Data Abstraction

IS 0020 Program Design and Software Tools

Pointer Assignments. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 18 October 29, The new Operator

IS 0020 Program Design and Software Tools

57:017, Computers in Engineering C++ Classes

IS 0020 Program Design and Software Tools

An inline function is one in which the function code replaces the function call directly. Inline class member functions

Chapter 16: Classes and Data Abstraction

9.1 Introduction. Integrated Time class case study Preprocessor wrapper Three types of handles on an object. Class functions

1 // Fig. 6.13: time2.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> Outline. 4 5 using std::cout; 6 7 #include <iomanip>

Classes and Data Abstraction. Topic 5

clarity. In the first form, the access specifier public : is needed to {

Chapter 9 Classes : A Deeper Look, Part 1

Computer Programming with C++ (21)

A Deeper Look at Classes

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

Computer Programming Class Members 9 th Lecture

Classes and Data Abstraction

Preview 9/20/2017. Object Oriented Programing with C++ Object Oriented Programing with C++ Object Oriented Programing with C++

Fundamentals of Programming Session 12

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. 1

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Classes and Data Abstraction. Topic 5

Object Oriented Design

W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls

Classes: A Deeper Look. Systems Programming

Introduction to Programming

Deitel Dive-Into Series: Dive-Into Cygwin and GNU C++

Lecture 18 Tao Wang 1

Fundamentals of Programming Session 25

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

Introduction Of Classes ( OOPS )

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Introduction to Programming

Classes: A Deeper Look, Part 2

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Object Oriented Design

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Fundamentals of Programming Session 23

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

Cpt S 122 Data Structures. Introduction to C++ Part II

Fast Introduction to Object Oriented Programming and C++

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

AN OVERVIEW OF C++ 1

Data Structures using OOP C++ Lecture 3

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 12: Classes and Data Abstraction

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Fundamentals of Programming Session 20

Fundamentals of Programming Session 24

Chapter 10 Introduction to Classes

Fundamentals of Programming Session 25

Fundamentals of Programming Session 15

Fundamentals of Programming Session 13

Fundamentals of Programming Session 4

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

Intermediate Programming, Spring 2017*

Introduction to Programming

Functions, Arrays & Structs

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

Friends and Overloaded Operators

Friends and Overloaded Operators

CSC1322 Object-Oriented Programming Concepts

Interview Questions of C++

Fundamentals of Programming Session 27

Fundamentals of Programming. Lecture 19 Hamed Rasifard

public : int min, hour ; T( ) //here constructor is defined inside the class definition, as line function. { sec = min = hour = 0 ; }

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

Functions and Recursion

EL2310 Scientific Programming

Classes and Objects. Types and Classes. Example. Object Oriented Programming

Chapter 15 - C++ As A "Better C"

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370

Constructor - example

Recharge (int, int, int); //constructor declared void disply();

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Functions, Arrays & Structs

Fundamentals of Programming Session 19

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

CSCE 110 PROGRAMMING FUNDAMENTALS

G205 Fundamentals of Computer Engineering. CLASS 3, Wed. Sept Stefano Basagni Fall 2004 M-W, 1:30pm-3:10pm

CS3157: Advanced Programming. Outline

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

III. Classes (Chap. 3)

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

System Design and Programming II

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

Class 15. Object-Oriented Development from Structs to Classes. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Operator Overloading in C++ Systems Programming

Lecture 7. Log into Linux New documents posted to course webpage

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Welcome 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:

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

IS 0020 Program Design and Software Tools


Transcription:

Fundamentals of Programming Session 24 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology

Outlines Data Members, set Functions and get Functions Constructors Destructors When Constructors and Destructors Are Called 2

Data Members, set Functions and get Functions 3

Data Members, set Functions and get Functions 4

Data Members, set Functions and get Functions 5

Data Members, set Functions and get Functions Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes Information hiding Class objects communicate across well-defined interfaces Implementation details hidden within classes themselves User-defined (programmer-defined) types: classes Data (data members) Functions (member functions or methods) Class instance: object 6

Data Members, set Functions and get Functions 7 Classes Model objects Attributes (data members) Behaviors (member functions) Defined using keyword class Member functions Methods Invoked in response to messages Member access specifiers public: Accessible wherever object of class in scope private: Accessible only to member functions of class protected:

8 1 classtime { 2 3 public: 4 5 void settime( int, int, int ); // set hour, minute, second 6 void printuniversal(); // print universal-time format 7 void printstandard(); // print standard-time format 8 9 private: 10 int hour; // 0-23 (24-hour clock format) 11 int minute; // 0-59 12 int second; // 0-59 13 14 }; // end class Time

Data Members, set Functions and get Functions 9 Class scope Data members, member functions Within class scope Class members Immediately accessible by all member functions Referenced by name Outside class scope Referenced through handles Object name, reference to object, pointer to object File scope Nonmember functions

Data Members, set Functions and get Functions Function scope Variables declared in member function Only known to function Variables with same name as class-scope variables Class-scope variable hidden Access with scope resolution operator (::) ClassName::classVariableName Variables only known to function they are defined in Variables are destroyed after function completion 10

Data Members, set Functions and get Functions Operators to access class members Identical to those for structs Dot member selection operator (.) Object Reference to object Arrow member selection operator (->) Pointers 11

1 // Demonstrating the class member access operators. and -> 2 // CAUTION: IN FUTURE EXAMPLES WE AVOID PUBLIC DATA! 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 // class Count definition 7 class Count { 8 public: 9 int x; 10 void print() 11 { 12 cout << x << endl; 13 } 14 }; // end class Count 12

15 int main() 16 { 17 Count counter; // create counter object 18 Count *counterptr = &counter; // create pointer to counter 19 Count &counterref = counter; // create reference to counter 20 cout << "Assign 1 to x and print using the object's name: "; 21 counter.x = 1; // assign 1 to data member x 22 counter.print(); // call member function print 23 cout << "Assign 2 to x and print using a reference: "; 24 counterref.x = 2; // assign 2 to data member x 25 counterref.print(); // call member function print 26 cout << "Assign 3 to x and print using a pointer: "; 27 counterptr->x = 3; // assign 3 to data member x 28 counterptr->print(); // call member function print 29 return 0; 30 } // end main Assign 1 to x and print using the object's name: 1 Assign 2 to x and print using a reference: 2 Assign 3 to x and print using a pointer: 3 13

Data Members, set Functions and get Functions Class member access Default private Explicitly set to private, public, protected Access to class s private data Controlled with access functions (accessor methods) Get function Read private data Set function Modify private data 14

Constructors Constructors Initialize data members Or can set later Same name as class No return type Initializers Passed as arguments to constructor In parentheses to right of class name before semicolon Class-type ObjectName( value1,value2, ); 15

16 1 // Member functions for class SalesPerson. 2 #include <iostream> 3 #include <iomanip> 4 using namespace std; 5 // class definition 6 class SalesPerson { 7 public: 8 SalesPerson(); // constructor 9 void getsalesfromuser(); // input sales from keyboard 10 void setsales( int, double ); // set sales for a month 11 void printannualsales(); // summarize and print sales 12 private: 13 double totalannualsales(); // utility function 14 double sales[ 12 ]; // 12 monthly sales figures 15 }; // end class SalesPerson

17 16 SalesPerson::SalesPerson() 17 { 18 for ( int i = 0; i < 12; i++ ) 19 sales[ i ] = 0.0; 20 } // end SalesPerson constructor 21 // get 12 sales figures from the user at the keyboard 22 void SalesPerson::getSalesFromUser() 23 { 24 double salesfigure; 25 for ( int i = 1; i <= 12; i++ ) { 26 cout << "Enter sales amount for month " << i << ": "; 27 cin >> salesfigure; 28 setsales( i, salesfigure ); 29 } // end for 30 } // end function getsalesfromuser 31 // set one of the 12 monthly sales figures; function subtracts 32 // one from month value for proper subscript in sales array

18 33 void SalesPerson::setSales( int month, double amount ) 34 { 35 // test for valid month and amount values 36 if ( month >= 1 && month <= 12 && amount > 0 ) 37 sales[ month - 1 ] = amount; // adjust for subscripts 0-11 38 else // invalid month or amount value 39 cout << "Invalid month or sales figure" << endl; 40 } // end function setsales 41 // print total annual sales (with help of utility function) 42 void SalesPerson::printAnnualSales() 43 { 44 cout << setprecision( 2 ) << fixed 45 << "\nthe total annual sales are: $" 46 << totalannualsales() << endl; // call utility function 47 } // end function printannualsales 48 // private utility function to total annual sales

19 49 double SalesPerson::totalAnnualSales() 50 { 51 double total = 0.0; // initialize total 52 for ( int i = 0; i < 12; i++ ) // summarize sales results 53 total += sales[ i ]; 54 return total; 55 } // end function totalannualsales 56 int main() 57 { 58 SalesPerson s; // create SalesPerson object s 59 s.getsalesfromuser(); // note simple sequential code; no 60 s.printannualsales(); // control structures in main 61 return 0; 62 } // end main

Enter sales amount for month 1: 5314.76 Enter sales amount for month 2: 4292.38 Enter sales amount for month 3: 4589.83 Enter sales amount for month 4: 5534.03 Enter sales amount for month 5: 4376.34 Enter sales amount for month 6: 5698.45 Enter sales amount for month 7: 4439.22 Enter sales amount for month 8: 5893.57 Enter sales amount for month 9: 4909.67 Enter sales amount for month 10: 5123.45 Enter sales amount for month 11: 4024.97 Enter sales amount for month 12: 5923.92 The total annual sales are: $60120.59 20

Constructors Constructors Can specify default arguments Default constructors Defaults all arguments OR Explicitly requires no arguments Can be invoked with no arguments Only one per class 21

22 1 #include <iostream> 2 #include <iomanip> 3 using namespace std; 4 5 classtime { 6 public: 7 Time( int = 0, int = 0, int = 0); // default constructor 8 void settime( int, int, int ); // set hour, minute, second 9 void printuniversal(); // print universal-time format 10 void printstandard(); // print standard-time format 11 private: 12 int hour; // 0-23 (24-hour clock format) 13 int minute; // 0-59 14 int second; // 0-59 15 }; // end class Time

// ensures all Time objects start in a consistent state 16 Time::Time( int hr, int min, int sec ) 17 { 18 settime( hr, min, sec ); // validate and set time 19 } // end Time constructor 20 // set new Time value using universal time, perform validity 21 // checks on the data values and set invalid values to zero 22 voidtime::settime( int h, int m, int s ) 23 { 24 hour = ( h >= 0 && h < 24 )? h : 0; 25 minute = ( m >= 0 && m < 60 )? m : 0; 26 second = ( s >= 0 && s < 60 )? s : 0; 27 } // end function settime 28 // print Time in universal format 29 void Time::printUniversal() 30 { 31 cout << setfill( '0' ) << setw( 2 ) << hour << ":" 32 << setw( 2 ) << minute << ":" 33 << setw( 2 ) << second; 34 } // end function printuniversal 23

24 30 // print Time in standard format 31 voidtime::printstandard() 32 { 33 cout << ( ( hour == 0 hour == 12 )? 12 : hour % 12 ) 34 << ":" << setfill( '0' ) << setw( 2 ) << minute 35 << ":" << setw( 2 ) << second 36 << ( hour < 12? " AM" : " PM" ); 37 38 } // end function printstandard

7 int main() 8 { 9 Time t1; // all arguments defaulted 10 Time t2( 2 ); // minute and second defaulted 11 Time t3( 21, 34 ); // second defaulted 12 Time t4( 12, 25, 42 ); // all values specified 13 Time t5( 27, 74, 99 ); // all bad values specified 14 cout << "Constructed with:\n\n" 15 << "all default arguments:\n "; 16 t1.printuniversal(); // 00:00:00 17 cout << "\n "; 18 t1.printstandard(); // 12:00:00 AM 25

26 19 cout << "\n\nhour specified; default minute and second:\n "; 20 t2.printuniversal(); // 02:00:00 21 cout << "\n "; 22 t2.printstandard(); // 2:00:00 AM 23 cout << "\n\nhour and minute specified; default second:\n "; 24 t3.printuniversal(); // 21:34:00 25 cout << "\n "; 26 t3.printstandard(); // 9:34:00 PM 27 cout << "\n\nhour, minute, and second specified:\n "; 28 t4.printuniversal(); // 12:25:42 29 cout << "\n "; 30 t4.printstandard(); // 12:25:42 PM 31 cout << "\n\nall invalid values specified:\n "; 32 t5.printuniversal(); // 00:00:00 33 cout << "\n "; 34 t5.printstandard(); // 12:00:00 AM 35 cout << endl; 36 return 0; 37 } // end main

27 Constructed with: all default arguments: 00:00:00 12:00:00 AM hour specified; default minute and second: 02:00:00 2:00:00 AM hour and minute specified; default second: 21:34:00 9:34:00 PM hour, minute, and second specified: 12:25:42 12:25:42 PM all invalid values specified: 00:00:00 12:00:00 AM

Destructors Destructors Special member function Same name as class Preceded with tilde (~) No arguments No return value Cannot be overloaded No explicit destructor Compiler creates empty destructor 28

Destructors Constructors and destructors Called implicitly by compiler Order of function calls Depends on order of execution When execution enters and exits scope of objects Generally, destructor calls reverse order of constructor calls 29

When Constructors and Destructors Are Called 30 Order of constructor, destructor function calls Global scope objects Constructors Before any other function (including main) Destructors When main terminates (or exit function called) Not called if program terminates with abort Automatic local objects Constructors When objects defined o Each time execution enters scope Destructors When objects leave scope o Execution exits block in which object defined Not called if program ends with exit or abort

When Constructors and Destructors Are Called Order of constructor, destructor function calls static local objects Constructors Exactly once When execution reaches point where object defined Destructors When main terminates or exit function called Not called if program ends with abort 31

1 #include <iostream> 2 using namespace std; 3 // Definition of class CreateAndDestroy. 4 class CreateAndDestroy { 5 public: 6 CreateAndDestroy( int, char * ); // constructor 7 ~CreateAndDestroy(); // destructor 8 private: 9 int objectid; 10 char *message; 11 }; // end class CreateAndDestroy 12 // constructor 13 CreateAndDestroy::CreateAndDestroy( 14 int objectnumber, char *messageptr ) 15 { 16 objectid = objectnumber; 17 message = messageptr; 18 cout << "Object " << objectid << " constructor runs " 19 << message << endl; 20 } // end CreateAndDestroy constructor 32

21 // destructor 22 CreateAndDestroy::~CreateAndDestroy() 23 { 24 // the following line is for pedagogic purposes only 25 cout << ( objectid == 1 objectid == 6? "\n" : "" ); 26 27 cout << "Object " << objectid << " destructor runs " 28 << message << endl; 29 30 } // end ~CreateAndDestroy destructor 31 32 void create( void ); // prototype 33 // global object 34 CreateAndDestroy first( 1, "(global before main)" ); 35 int main() 36 { 37 cout << "\nmain FUNCTION: EXECUTION BEGINS" << endl; 38 CreateAndDestroy second( 2, "(local automatic in main)" ); 39 static CreateAndDestroy third( 40 3, "(local static in main)" ); 33

41 create(); // call function to create objects 42 cout << "\nmain FUNCTION: EXECUTION RESUMES" << endl; 43 CreateAndDestroy fourth( 4, "(local automatic in main)" ); 44 cout << "\nmain FUNCTION: EXECUTION ENDS" << endl; 45 return 0; 46 } // end main 47 // function to create objects 48 void create( void ) 49 { 50 cout << "\ncreate FUNCTION: EXECUTION BEGINS" << endl; 51 CreateAndDestroy fifth( 5, "(local automatic in create)" ); 52 static CreateAndDestroy sixth( 53 6, "(local static in create)" ); 54 CreateAndDestroy seventh( 55 7, "(local automatic in create)" ); 56 cout << "\ncreate FUNCTION: EXECUTION ENDS\" << endl; 57 } // end function create 34

Object 1 constructor runs (global before main) MAIN FUNCTION: EXECUTION BEGINS Object 2 constructor runs (local automatic in main) Object 3 constructor runs (local static in main) CREATE FUNCTION: EXECUTION BEGINS Object 5 constructor runs (local automatic in create) Object 6 constructor runs (local static in create) Object 7 constructor runs (local automatic in create) CREATE FUNCTION: EXECUTION ENDS Object 7 destructor runs (local automatic in create) Object 5 destructor runs (local automatic in create) MAIN FUNCTION: EXECUTION RESUMES Object 4 constructor runs (local automatic in main) MAIN FUNCTION: EXECUTION ENDS Object 4 destructor runs (local automatic in main) Object 2 destructor runs (local automatic in main) Object 6 destructor runs (local static in create) Object 3 destructor runs (local static in main) 35 Object 1 destructor runs (global before main)