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

Size: px
Start display at page:

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

Transcription

1 CISC11 Introduction to Computer Science Dr. McCoy Lecture 1 October 29, 2009 Pointer Assignments Pointer variables can be "assigned": int *p1, *p2; p2 = p1; Assigns one pointer to another "Make p2 point to where p1 points" Do not confuse with: *p1 = *p2; Assigns "value pointed to" by p1, to "value pointed to" by p2 1 Copyright 2010 Pearson Addison Wesley Pointer Assignments Graphic: Display 10.1 Uses of the Assignment Operator with Pointer Variables The new Operator Since pointers can refer to variables No "real" need to have a standard identifier Can dynamically allocate variables Operator new creates variables No identifiers to refer to them Just a pointer! p1 = new int; Creates new "nameless" variable, and assigns p1 to "point to" it Can access with *p1 Use just like ordinary variable Copyright 2010 Pearson Addison Wesley. All rights reserved Copyright 2010 Pearson Addison Wesley. 10 Basic Pointer Manipulations Example: Display 10.2 Basic Pointer Manipulations (1 of 2) Basic Pointer Manipulations Example: Display 10.2 Basic Pointer Manipulations (2 of 2) Copyright 2010 Pearson Addison Wesley. All rights reserved Copyright 2010 Pearson Addison Wesley. All rights reserved

2 Basic Pointer Manipulations Graphic: Display 10.3 Explanation of Display 10.2 More on new Operator Creates new dynamic variable Returns pointer to the new variable If type is class type: Constructor is called for new object Can invoke different constructor with initializer arguments: MyClass *mcptr; mcptr = new MyClass(.0, 17); Can still initialize non class types: int *n; n = new int(17); //Initializes *n to 17 Copyright 2010 Pearson Addison Wesley. All rights reserved Copyright 2010 Pearson Addison Wesley. 10 Pointers and Functions Memory Management Pointers are full fledged types Can be used just like other types Can be function parameters Can be returned from functions Example: int* findotherpointer(int* p); This function declaration: Has "pointer to an int" parameter Returns "pointer to an int" variable Heap Also called "freestore" Reserved for dynamically allocated variables All new dynamic variables consume memory in freestore If too many could use all freestore memory Future "new" operations will fail if freestore is "full" Copyright 2010 Pearson Addison Wesley Copyright 2010 Pearson Addison Wesley Checking new Success new Success New Compiler Older compilers: Test if null returned by call to new: int *p; p = new int; if (p == NULL) { cout << "Error: Insufficient memory.\n"; exit(1); } Newer compilers: If new operation fails: Program terminates automatically Produceserror error message Still good practice to use NULL check If new succeeded, program continues Copyright 2010 Pearson Addison Wesley. 10 Copyright 2010 Pearson Addison Wesley

3 Freestore Size delete Operator Varies with implementations Typically large Most programs won t use all memory Memory management Still good practice Solid software engineering principle Memory IS finite Regardless of how much there is! De allocate dynamic memory When no longer needed Returns memory to freestore Example: int *p; p = new int(5); //Some processing delete p; De allocates dynamic memory "pointed to by pointer p" Literally "destroys" memory Copyright 2010 Pearson Addison Wesley Copyright 2010 Pearson Addison Wesley Dangling Pointers Dynamic Arrays delete p; Destroys dynamic memory But p still points there! Called "dangling pointer" If p is then dereferenced ( *p ) Unpredicatable results! Often disastrous! Avoid dangling pointers Assign pointer to NULL after delete: delete p; p = NULL; Array variables Really pointer variables! Standard array Fixed size Dynamic array Size not specified at programming time Determined while program running Copyright 2010 Pearson Addison Wesley Copyright 2010 Pearson Addison Wesley Array Variables Array Variables Pointers Recall: arrays stored in memory addresses, sequentially Array variable "refers to" first indexed variable So array variable is a kind of pointer variable! Example: int a[10]; int * p; a and p are both pointer variables! Recall previous example: int a[10]; typedef int* IntPtr; IntPtr p; a and p are pointer variables Can perform assignments: p = a; // Legal. p now points where a points To first indexed variable of array a a = p; // ILLEGAL! Array pointer is CONSTANT pointer! Copyright 2010 Pearson Addison Wesley Copyright 2010 Pearson Addison Wesley

4 Array Variables Pointers Dynamic Arrays Array variable int a[10]; MORE than a pointer variable "const int *" type Array was allocated in memory already Variable a MUST point there always! Cannot be changed! In contrast to ordinary pointers Which can (& typically do) change Array limitations Must specify size first May not know until program runs! Must "estimate" maximum size needed Sometimes OK, sometimes not "Wastes" memory Dynamic arrays Can grow and shrink as needed Copyright 2010 Pearson Addison Wesley Copyright 2010 Pearson Addison Wesley Creating Dynamic Arrays Deleting Dynamic Arrays Very simple! Use new operator Dynamically allocate with pointer variable Treat like standard arrays Example: typedef double * DoublePtr; DoublePtr d; d = new double[10]; //Size in brackets Creates dynamically allocated array variable d, with ten elements, base type double Allocated dynamically at run time So should be destroyed at run time Simple again. Recall Example: d = new double[10]; //Processing delete [] d; De allocates all memory for dynamic array Brackets indicate "array" is there Recall: d still points there! Should set d = NULL; Copyright 2010 Pearson Addison Wesley Copyright 2010 Pearson Addison Wesley. 10 Function that Returns an Array Destructor Need Array type NOT allowed as return type of function Dynamically allocated variables Do not go away until "deleted" Example: int [] somefunction(); // ILLEGAL! Instead return pointer to array base type: int* somefunction(); // LEGAL! If pointers are only private member data They dynamically allocate "real" l"dt data In constructor Must have means to "deallocate" when object is destroyed Answer: destructor! Copyright 2010 Pearson Addison Wesley Copyright 2010 Pearson Addison Wesley. 10 2

5 Destructors Copy Constructors Opposite of constructor Automatically called when object is out of scope Default version only removes ordinary variables, not dynamic variables Automatically called when: 1. Class object declared and initialized to other object 2. When function returns class type object 3. When argument of class type is "plugged in" as actual argument to call by value parameter Defined like constructor, just add ~ MyClass::~MyClass() { //Perform delete clean up duties } Requires "temporary copy" of object Copy constructor creates it Default copy constructor Like default "=", performs member wise copy Pointers write own copy constructor! Copyright 2010 Pearson Addison Wesley Copyright 2010 Pearson Addison Wesley Summary 1 Summary 2 Pointer is memory address Provides indirect reference to variable Dynamic variables Created and destroyed while program runs Freestore Memory storage for dynamic variables Dynamically allocated arrays Size determined as program runs Class destructor Special member function Automatically destroys objects Copy constructor Single argument member function Called automatically when temp copy needed Assignment operator Must be overloaded as member function Returns reference for chaining Copyright 2010 Pearson Addison Wesley Copyright 2010 Pearson Addison Wesley Go over Homework 6.6 Complex Class Header file contains class definition complex.h note preprocessor directives so don t load it more than once! Class implementation complex.cc note preprocessor directives for loading header; must be compiled. Driver Program (19-complex.cc) note preprocessor directives for loading header. ~/mccoy/class/cisc11/examples Implementing a Time Abstract Data Type with a class Advantages of using classes Simplify programming Interfaces Hide implementation Software reuse Composition (aggregation) Class objects included as members of other classes Inheritance New classes derived from old 30 5

6 6.6 Class Scope and Accessing Class Members Class Scope and Accessing Class Members 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 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 6.6 Class Scope and Accessing Class Members Operators to access class members Identical to those for structs Dot member selection operator (.) Object Reference to object Arrow member selection operator (->) Pointers 33 1 // Fig. 6.: fig06_0.cpp 2 // Demonstrating the class member access operators. and -> 3 // // CAUTION: IN FUTURE EXAMPLES WE AVOID PUBLIC DATA! 5 #include <iostream> 6 7 using std::cout; using std::endl; 9 10 // class Count definition class Count { Data member x public to 12 illustrate class member access 13 public: operators; typically data 1 int x; members private void print() 17 { 1 cout << x << endl; 19 } fig06_0.cpp (1 of 2) }; // end class Count 23 int main() 2 { 25 Count counter; // create counter object 26 Count *counterptr // create pointer to counter = &counter; 27 Count &counterref = counter; // Use create dot member reference selection to counter 2 29 operator for counter object. cout << "Assign 1 to x and print using the object's name: "; 30 counter.x = 1; // assign 1 to data member x 31 counter.print(); // call member Use function dot member printselection operator for counterref 33 cout << "Assign 2 to x and print using reference a reference: to object. "; 3 counterref.x = 2; // assign 2 to data member x 35 counterref.print(); // call member Use function arrow print member selection operator for counterptr cout << "Assign 3 to x and print using pointer a pointer: to object. "; 3 counterptr->x = 3; // assign 3 to data member x 39 counterptr->print(); // call member function print fig06_0.cpp (2 of 2) fig06_0.cpp output (1 of 1) 35 Another Example Rational Number class (in same directory) 0 1 return 0; 2 3 } // 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:

7 6.7 Separating Interface from Implementation Separating Interface from Implementation 3 Separating interface from implementation Advantage Easier to modify programs Disadvantage Header files Portions of implementation Inline member functions Hints about other implementation private members Can hide more with proxy class Header files Class definitions and function prototypes Included in each file using class #include File extension.h Source-code files Member function definitions Same base name Convention Compiled and linked 1 // Fig. 6.5: time1.h 2 // Declaration of class Time. 3 // Member functions are defined in time1.cpp Preprocessor code to prevent 5 multiple inclusions. // prevent multiple inclusions of header file 6 #ifndef TIME1_H 7 #define TIME1_H Code between these directives 9 // Time abstract data type definition not included if name 10 class Time { Naming directive defines TIME1_H name convention: TIME1_H. already defined. header file name with 12 public: 13 Time(); underscore replacing period. // constructor 1 void settime( // set hour, minute, int, int, int ); second 15 void printuniversal(); // print universal-time format 16 void printstandard(); // print standard-time format 17 1 private: 19 int hour; // 0-23 (2-hour clock format) 20 int minute; // int second; // 0-59 time1.h (1 of 1) 39 1 // Fig. 6.6: time1.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> 5 using std::cout; 6 7 #include <iomanip> 9 using std::setfill; 10 using std::setw; Include header file time1.h. 12 // include definition of class Time from time1.h 13 #include "time1.h" 1 15 // Time constructor initializes each data member to zero. 16 // Ensures all Time objects Name start of in header a consistent file enclosed state. 17 Time::Time() in quotes; angle brackets 1 { cause preprocessor to assume 19 hour = minute = second = 0; header part of C++ Standard 20 Library. 21 } // end Time constructor time1.cpp (1 of 3) 0 23 }; // end class Time 2 25 #endif 23 // Set new Time value using universal time. Perform validity 2 // checks on the data values. Set invalid values to zero. 25 void Time::setTime( int h, int m, int s ) 26 { 27 hour = ( h >= 0 && h < 2 )? h : 0; 2 minute = ( m >= 0 && m < 60 )? m : 0; 29 second = ( s >= 0 && s < 60 )? s : 0; time1.cpp (2 of 3) 1 2 // print Time in standard format 3 void Time::printStandard() { 5 cout << ( ( hour == 0 hour == 12 )? 12 : hour % 12 ) 6 << ":" << setfill( '0' ) << setw( 2 ) << minute 7 << ":" << setw( 2 ) << second << ( hour < 12? " AM" : " PM" ); time1.cpp (3 of 3) } // end function settime 9 50 } // end function printstandard 33 // print Time in universal format 3 void Time::printUniversal() 35 { 36 cout << setfill( '0' ) << setw( 2 ) << hour << ":" 37 << setw( 2 ) << minute << ":" 3 << setw( 2 ) << second; 39 0 } // end function printuniversal 1 7

8 1 // Fig. 6.7: fig06_07.cpp 2 // Program to test class Time. 3 // NOTE: This file must be compiled with time1.cpp. #include <iostream> 5 6 using std::cout; Include header file time1.h 7 using std::endl; 9 to ensure correct // include definition of class Time from creation/manipulation time1.h and 10 #include "time1.h" determine size of Time class object. 12 int main() 13 { 1 Time t; // instantiate object t of class Time // output Time object t's initial values 17 cout << "The initial universal time is "; 1 t.printuniversal(); // 00:00:00 19 cout << "\nthe initial standard time is "; 20 t.printstandard(); // 12:00:00 AM 21 t.settime( 13, 27, 6 ); // change time fig06_07.cpp (1 of 2) 3 2 // output Time object t's new values 25 cout << "\n\nuniversal time after settime is "; 26 t.printuniversal(); // 13:27:06 27 cout << "\nstandard time after settime is "; 2 t.printstandard(); // 1:27:06 PM t.settime( 99, 99, 99 ); // attempt invalid settings 31 // output t's values after specifying invalid values 33 cout << "\n\nafter attempting invalid settings:" 3 << "\nuniversal time: "; 35 t.printuniversal(); // 00:00:00 36 cout << "\nstandard time: "; 37 t.printstandard(); // 12:00:00 AM 3 cout << endl; 39 0 return 0; 1 2 // end main } The initial universal time is 00:00:00 The initial standard time is 12:00:00 AM fig06_07.cpp (2 of 2) fig06_07.cpp output (1 of 1) 23 Universal time after settime is 13:27:06 Standard time after settime is 1:27:06 PM 6. Controlling Access to Members Access modes private Default access mode Accessible to member functions and friends public Accessible to any function in program with handle to class object protected Chapter // Fig. 6.: fig06_0.cpp 2 // Demonstrate errors resulting from attempts 3 // to access private class members. #include <iostream> fig06_0.cpp 5 (1 of 1) 6 using std::cout; 7 // include definition of class Time from time1.h 9 #include "time1.h" 10 int main() 12 { Recall data member hour is object 13 Time t; // create Time private; attempts to access 1 15 private members results in 16 t.hour = 7; // error: 'Time::hour' error. is not accessible Data member minute also 17 private; attempts to access 1 // error: 'Time::minute' is not accessible private members produces 19 cout << "minute = " << t.minute; error return 0; 6 23 } // end main D:\cpphtp_examples\ch06\Fig6_06\Fig06_06.cpp(16) : error C: 'hour' : cannot access private member declared in class 'Time' D:\cpphtp_examples\ch06\Fig6_06\Fig06_06.cpp(19) : error C: 'minute' : cannot access private member declared in class 'Time' fig06_0.cpp output (1 of 1) Errors produced by attempting to access private members Controlling Access to Members Class member access Default private Explicitly set to private, public, protected struct member access Default public 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

9 6.9 Access Functions and Utility Functions Access functions public Read/display data Predicate functions Check conditions Utility functions (helper functions) private Support operation of public member functions Not intended for direct client use 9 1 // Fig. 6.9: salesp.h 2 // SalesPerson class definition. 3 // Member functions defined in salesp.cpp. #ifndef SALESP_H 5 #define SALESP_H 6 7 class SalesPerson { Set access function 9 public: performs validity 10 SalesPerson(); // constructorchecks. void getsalesfromuser(); // input sales from keyboard 12 void setsales( int, double // set sales for a month ); 13 void printannualsales(); private utility // summarize and print sales 1 function. 15 private: 16 double totalannualsales(); // utility function 17 double sales[ 12 ]; // 12 monthly sales figures 1 19 // end class SalesPerson }; #endif salesp.h (1 of 1) 50 1 // Fig. 6.10: salesp.cpp 2 // Member functions for class SalesPerson. 3 #include <iostream> 5 using std::cout; 6 using std::cin; 7 using std::endl; using std::fixed; 9 10 #include <iomanip> 12 using std::setprecision; 13 1 // include SalesPerson class definition from salesp.h 15 #include "salesp.h" // initialize elements of array sales to SalesPerson::SalesPerson() 19 { 20 for ( int i = 0; i < 12; i++ ) 21 sales[ i ] = 0.0; salesp.cpp (1 of 3) // get 12 sales figures from the user at the keyboard 26 void SalesPerson::getSalesFromUser() 27 { 2 double salesfigure; for ( int i = 1; i <= 12; i++ ) { 31 cout << "Enter sales amount for month " << i << ": "; cin >> salesfigure; 33 setsales( i, salesfigure ); 3 35 } // end for } // end function getsalesfromuser 3 39 // set one of the 12 monthly sales figures; function subtracts 0 // one from month value for proper subscript in sales array Set access function performs 1 void SalesPerson::setSales( int month, double amount ) validity checks. 2 { 3 // test for valid month and amount values if ( month >= 1 && month <= 12 && amount > 0 ) 5 sales[ month - 1 ] = amount; // adjust for subscripts 0- salesp.cpp (2 of 3) } // end SalesPerson constructor else // invalid month or amount value cout << "Invalid month or sales figure" << endl; } // end function setsales // print total annual sales (with help of utility function) salesp.cpp (3 of 3) 53 void SalesPerson::printAnnualSales() 5 { 55 cout << setprecision( 2 ) << fixed 56 << "\nthe total annual sales are: $" 57 << totalannualsales() << endl; // call utility function 5 59 } // end function printannualsales private utility function to // private utility function to total annual sales help function 62 double SalesPerson::totalAnnualSales() 63 { printannualsales; encapsulates es logic of 6 double total = 0.0; // initialize total manipulating sales array for ( int i = 0; i < // summarize sales results 12; i++ ) 67 total += sales[ i ]; 6 69 return total; } // end function totalannualsales 1 // Fig. 6.: fig06_.cpp 2 // Demonstrating a utility function. 3 // Compile this program with salesp.cpp fig06_.cpp 5 // include SalesPerson class definition from salesp.h (1 of 1) 6 #include "salesp.h" 7 int main() Simple sequence of member { 9 10 SalesPerson s; function calls; logic // create SalesPerson object s encapsulated in member 12 s.getsalesfromuser(); functions. // note simple sequential code; no 13 s.printannualsales(); // control structures in main 1 15 return 0; } // end main 5 9

10 Enter sales amount for month 1: Enter sales amount for month 2: Enter sales amount for month 3: 59.3 Enter sales amount for month : Enter sales amount for month 5: Enter sales amount for month 6: Enter sales amount for month 7: 39. Enter sales amount for month : Enter sales amount for month 9: Enter sales amount for month 10: Enter sales amount for month : Enter sales amount for month 12: The total annual sales are: $ fig06_.cpp output (1 of 1) Initializing Class Objects: 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, ); Using Default Arguments with 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 57 1 // Fig. 6.12: time2.h 2 // Declaration of class Time. 3 // Member functions defined in time2.cpp. 5 // prevent multiple inclusions of header file 6 #ifndef TIME2_H 7 #define TIME2_H 9 // Time abstract data type definition Default constructor specifying 10 class Time { all arguments. 12 public: 13 Time( int = 0, int = 0, int = 0); // default constructor 1 void settime( int, int, int ); // set hour, minute, second 15 void printuniversal(); // print universal-time format 16 void printstandard(); // print standard-time format 17 1 private: 19 int hour; // 0-23 (2-hour clock format) 20 int minute; // int second; // 0-59 time2.h (1 of 1) 5 23 }; // end class Time 2 25 #endif 1 // Fig. 6.13: time2.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> 5 using std::cout; 6 7 #include <iomanip> time2.cpp (1 of 3) // set new Time value using universal time, perform validity 2 // checks on the data values and set invalid values to zero 25 void Time::setTime( int h, int m, int s ) 26 { 27 hour = ( h >= 0 && h < 2 )? h : 0; 2 minute = ( m >= 0 && m < 60 )? m : 0; 29 second = ( s >= 0 && s < 60 )? s : 0; time2.cpp (2 of 3) 60 9 using std::setfill; 10 using std::setw; 12 // include definition of class Time from time2.h 13 #include "time2.h" 1 Constructor calls settime 15 // Time constructor initializes each data member to zero; to validate passed (or default) 16 // ensures all Time objects start in a consistent state values. 17 Time::Time( int hr, int min, int sec ) 1 { 19 settime( hr, min, sec ); // validate and set time } // end Time constructor } // end function settime 33 // print Time in universal format 3 void Time::printUniversal() 35 { 36 cout << setfill( '0' ) << setw( 2 ) << hour << ":" 37 << setw( 2 ) << minute << ":" 3 << setw( 2 ) << second; 39 0 } // end function printuniversal 1 10

11 2 // print Time in standard format 3 void Time::printStandard() { 5 cout << ( ( hour == 0 hour == 12 )? 12 : hour % 12 ) 6 << ":" << setfill( '0' ) << setw( 2 ) << minute 7 << ":" << setw( 2 ) << second << ( hour < 12? " AM" : " PM" ); 9 50 } // end function printstandard time2.cpp (3 of 3) 61 1 // Fig. 6.1: fig06_1.cpp 2 // Demonstrating a default constructor for class Time. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 7 // include definition of class Time from time2.h 9 #include "time2.h" fig06_1.cpp (1 of 2) int main() 12 { 13 Time t1; // all arguments defaulted 1 Time t2( 2 ); // minute and second defaulted 15 Time t3( 21, 3 ); // second defaulted 16 Time t( 12, 25, 2 // all values specified ); 17 Time t5( 27, 7, 99 ); // all bad values specified Initialize Time objects using default arguments cout << "Constructed with:\n\n" 20 << "all default arguments:\n "; 21 t1.printuniversal(); // 00:00:00 cout << "\n "; 23 t1.printstandard(); // 12:00:00 AM Initialize Time object with invalid values; validity checking will set values to cout << "\n\nhour specified; default minute and second:\n "; 26 t2.printuniversal(); // 02:00:00 27 cout << "\n "; 2 t2.printstandard(); // 2:00:00 AM cout << "\n\nhour and minute specified; default second:\n "; 31 t3.printuniversal(); // 21:3:00 cout << "\n "; 33 t3.printstandard(); // 9:3:00 PM fig06_1.cpp (2 of 2) 63 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 fig06_1.cpp output (1 of 1) cout << "\n\nhour, minute, and second specified:\n "; 36 t.printuniversal(); // 12:25:2 37 cout << "\n "; 3 t.printstandard(); // 12:25:2 PM 39 t5 constructed with invalid 0 cout << "\n\nall invalid values specified:\n "; arguments; values set to 0. 1 t5.printuniversal(); // 00:00:00 2 cout << "\n "; 3 t5.printstandard(); // 12:00:00 AM cout << endl; 5 6 return 0; hour and minute specified; default second: 21:3:00 9:3:00 PM hour, minute, and second specified: 12:25:2 12:25:2 PM all invalid values specified: 00:00:00 12:00:00 AM 7 } // end main 6.12 Destructors Using Set and Get Functions 66 Destructors Special member function Same name as class Preceded with tilde (~) No arguments No return value Cannot be overloaded Performs termination housekeeping Before system reclaims object s memory Reuse memory for new objects No explicit destructor Compiler creates empty destructor Set functions Perform validity checks before modifying private data Notify if invalid values Indicate with return values Get functions Query functions Control format of data returned

12 1 // Fig. 6.1: time3.h 2 // Declaration of class Time. 3 // Member functions defined in time3.cpp 5 // prevent multiple inclusions of header file 6 #ifndef TIME3_H 7 #define TIME3_H time3.h (1 of 2) void printuniversal(); // output universal-time format 26 void printstandard(); // output standard-time format 27 2 private: 29 int hour; // 0-23 (2-hour clock format) 30 int minute; // int second; // 0-59 time3.h (2 of 2) 6 9 class Time { 33 }; // end clas Time 10 public: 12 Time( int = 0, int = 0, int = 0 ); // default constructor 13 1 // set functions 15 void settime( int, int, int ); // set hour, minute, second 16 void sethour( int ); // set hour 17 void setminute( int ); // set minute 1 void setsecond( int ); // set second // get functions 21 int gethour(); // return hour int getminute(); // return minute 23 int getsecond(); // return second Set functions. Get functions #endif 2 1 // Fig. 6.19: time3.cpp 2 // Member-function definitions for Time class. 3 #include <iostream> 5 using std::cout; 6 7 #include <iomanip> 9 using std::setfill; 10 using std::setw; 12 // include definition of class Time from time3.h 13 #include "time3.h" 1 15 // constructor function to initialize private data; 16 // calls member function settime to set variables; 17 // default values are 0 (see class definition) 1 Time::Time( int hr, int min, int sec ) 19 { 20 settime( hr, min, sec ); 21 } // end Time constructor time3.cpp (1 of ) 69 2 // set hour, minute and second values 25 void Time::setTime( int h, int m, int s ) 26 { 27 sethour( h ); time3.cpp (2 of ) 2 setminute( m ); 29 setsecond( s ); 30 Call set functions to perform 31 } // end function settime validity checking. 33 // set hour value 3 void Time::setHour( int h ) 35 { 36 hour = ( h >= 0 && h < 2 )? h : 0; 37 3 } // end function sethour 39 Set functions perform validity 0 // set minute value checks before modifying data. 1 void Time::setMinute( int m ) 2 { 3 minute = ( m >= 0 && m < 60 )? m : 0; 5 } // end function setminute // set second value void Time::setSecond( int s ) 9 { 50 second = ( s >= 0 && s < 60 )? s : 0; } // end function setsecond 53 5 // return hour value 55 int Time::getHour() 56 { 57 return hour; 5 59 } // end function gethour // return minute value 62 int Time::getMinute() 63 { 6 return minute; } // end function getminute 67 Set function performs validity checks before modifying data. Get functions allow client to read data. time3.cpp (3 of ) 71 6 // return second value 69 int Time::getSecond() 70 { 71 return second; } // end function getsecond Get function allows client to 7 read data. 75 // print Time in universal format 76 void Time::printUniversal() 77 { 7 cout << setfill( '0' ) << setw( 2 ) << hour << ":" 79 << setw( 2 ) << minute << ":" 0 << setw( 2 ) << second; 1 2 } // end function printuniversal 3 // print Time in standard format 5 void Time::printStandard() 6 { 7 cout << ( ( hour == 0 hour == 12 )? 12 : hour % 12 ) << ":" << setfill( '0' ) << setw( 2 ) << minute 9 << ":" << setw( 2 ) << second 90 << ( hour < 12? " AM" : " PM" ); time3.cpp ( of ) } // end function printstandard 12

13 1 // Fig. 6.20: fig06_20.cpp 2 // Demonstrating the Time class set and get functions 3 #include <iostream> 5 using std::cout; 6 using std::endl; 7 // include definition of class Time from time3.h 9 #include "time3.h" 10 void incrementminutes( Time &, const int ); // prototype int main() 1 { 15 Time t; // create Time object // set time individual set functions using 1 t.sethour( 17 ); // set hour to valid value 19 t.setminute( 3 ); // set minute to valid value 20 t.setsecond( 25 ); // set second to valid value Invoke set functions to set valid values. fig06_20.cpp (1 of 3) 73 // use get functions to obtain hour, minute and second 23 cout << "Result of setting all valid values:\n" 2 << " Hour: " << t.gethour() Attempt to set invalid values 25 << " Minute: " << t.getminute() using set functions. fig06_20.cpp 26 << " Second: " << t.getsecond(); (2 of 3) 27 2 // set time using individual set functions 29 t.sethour( 23 ); // invalid hour set to 0 30 t.setminute( 3 ); // set minute to valid value 31 t.setsecond( 6373 ); // invalid second set to 0 Invalid values result in setting data members to // display hour, minute and second after setting 3 // invalid hour and second values 35 cout << "\n\nresult of attempting to set invalid hour and" 36 << " second:\n Hour: " << t.gethour() Modify data members using 37 << " Minute: " << t.getminute() function settime. 3 << " Second: " << t.getsecond() << "\n\n"; 39 0 t.settime(, 5, 0 ); // set time 1 incrementminutes( t, 3 ); // increment t's minute by return 0; 5 } // end main 6 7 // add specified number of minutes to a Time object void incrementminutes( Time &tt, const int count ) 9 { 50 cout << "Incrementing minute " << count 51 << " times:\nstart time: "; 52 tt.printstandard(); 53 5 for ( int i = 0; i < count; i++ ) { 55 tt.setminute( ( tt.getminute() + 1 ) % 60 ); if ( tt.getminute() == 0 ) 5 tt.sethour( ( tt.gethour() + 1 ) % 2); cout << "\nminute + 1: "; 61 tt.printstandard(); fig06_20.cpp Using get functions (3 of to 3) read data and set functions to modify data. 75 Result of setting all valid values: Hour: 17 Minute: 3 Second: 25 Result of attempting to set invalid hour and second: Hour: 0 Minute: 3 Second: 0 Incrementing minute 3 times: Start time: :5:00 AM Attempting to set data minute + 1: :59:00 AM minute + 1: 12:00:00 PM members with invalid values minute + 1: 12:01:00 PM results in error message and members set to 0. fig06_20.cpp output (1 of 1) } // end for 6 65 cout << endl; } // end function incrementminutes 13

Chapter 6: Classes and Data Abstraction

Chapter 6: Classes and Data Abstraction Chapter 6: Classes and Data Abstraction 1 6.1 Introduction 6.2 Structure Definitions 6.3 Accessing Structure Members 6.4 Implementing a User-Defined Type Time with a struct 6.5 Implementing a Time Abstract

More information

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>

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> CISC11 Introduction to Computer Science Dr. McCoy Lecture 20 November, 2009. Using Default Arguments with Constructors Constructors Can specify default arguments Default constructors Defaults all arguments

More information

57:017, Computers in Engineering C++ Classes

57:017, Computers in Engineering C++ Classes 57:017, Computers in Engineering C++ Classes Copyright 1992 2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Introduction Object-oriented programming (OOP) Encapsulates

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3 Jan 20, 2004 Quiz 1 2 Average: about 3.8 More than half obtained: 4 + Highest is 8 Need more work/practice! Quiz 1

More information

Chapter 16: Classes and Data Abstraction

Chapter 16: Classes and Data Abstraction Chapter 16: Classes and Data Abstraction 16.1 Introduction 16.2 Implementing a Time Abstract Data Type with a Class 16.3 Class Scope and Accessing Class Members 16.4 Separating Interface from Implementation

More information

More C++ Classes. Systems Programming

More C++ Classes. Systems Programming More C++ Classes Systems Programming C++ Classes Preprocessor Wrapper Time Class Case Study Class Scope and Assessing Class Members Using handles to access class members Access and Utility Functions Destructors

More information

Fundamentals of Programming Session 24

Fundamentals of Programming Session 24 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

More information

Classes: A Deeper Look

Classes: A Deeper Look Classes: A Deeper Look 1 Introduction Implementing a Time Abstract Data Type with a class Class Scope and Accessing Class Members Separating Interface from Implementation Controlling Access to Members

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3: Classes May 24, 2004 2 Classes Structure Definitions 3 Structures Aggregate data types built using elements of other

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 5: Classes September 14, 2004 Structure Definitions 2 Structures Aggregate data types built using elements of other types

More information

Introduction to Programming session 24

Introduction to Programming session 24 Introduction to Programming session 24 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel sslides Sharif Universityof Technology Outlines Introduction

More information

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

9.1 Introduction. Integrated Time class case study Preprocessor wrapper Three types of handles on an object. Class functions 1 9 Classes: A Deeper Look, Part 1 OBJECTIVES In this chapter you ll learn: How to use a preprocessor p wrapper to prevent multiple definition errors caused by including more than one copy of a header

More information

Computer Programming with C++ (21)

Computer Programming with C++ (21) Computer Programming with C++ (21) Zhang, Xinyu Department of Computer Science and Engineering, Ewha Womans University, Seoul, Korea zhangxy@ewha.ac.kr Classes (III) Chapter 9.7 Chapter 10 Outline Destructors

More information

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

An inline function is one in which the function code replaces the function call directly. Inline class member functions Inline Functions An inline function is one in which the function code replaces the function call directly. Inline class member functions if they are defined as part of the class definition, implicit if

More information

A Deeper Look at Classes

A Deeper Look at Classes A Deeper Look at Classes 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

More information

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

W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls 1 W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls 2 7.4 friend Functions and friend Classes friend function and friend classes Can access private

More information

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved. Chapter 10 Pointers and Dynamic Arrays Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives Pointers Pointer variables Memory management Dynamic Arrays Creating and using Pointer arithmetic

More information

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo Chapter 10 Pointers and Dynamic Arrays 1 Learning Objectives Pointers Pointer variables Memory management Dynamic Arrays Creating and using Pointer arithmetic Classes, Pointers, Dynamic Arrays The this

More information

Classes: A Deeper Look. Systems Programming

Classes: A Deeper Look. Systems Programming Classes: A Deeper Look Systems Programming Deeper into C++ Classes const objects and const member functions Composition Friendship this pointer Dynamic memory management new and delete operators static

More information

Classes: A Deeper Look, Part 2

Classes: A Deeper Look, Part 2 10 But what, to serve our private ends, Forbids the cheating of our friends? Charles Churchill Instead of this absurd division into sexes they ought to class people as static and dynamic. Evelyn Waugh

More information

Computer Programming Class Members 9 th Lecture

Computer Programming Class Members 9 th Lecture Computer Programming Class Members 9 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2015 Eom, Hyeonsang All Rights Reserved Outline Class

More information

Chapter 9 Classes : A Deeper Look, Part 1

Chapter 9 Classes : A Deeper Look, Part 1 Chapter 9 Classes : A Deeper Look, Part 1 C++, How to Program Deitel & Deitel Fall 2016 CISC1600 Yanjun Li 1 Time Class Case Study Time Class Definition: private data members: int hour; int minute; int

More information

Classes and Data Abstraction. Topic 5

Classes and Data Abstraction. Topic 5 Classes and Data Abstraction Topic 5 Classes Class User Defined Data Type Object Variable Data Value Operations Member Functions Object Variable Data Value Operations Member Functions Object Variable Data

More information

Classes and Data Abstraction

Classes and Data Abstraction 6 Classes and Data Abstraction Objectives To understand the software engineering concepts of encapsulation and data hiding. To understand the notions of data abstraction and abstract data types (ADTs).

More information

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

clarity. In the first form, the access specifier public : is needed to { Structure Time CSC 211 Intermediate Programming Classes in C++ // Create a structure, set its members, and print it. struct Time // structure definition int hour; // 0-23 int minute; // 0-59 int second;

More information

Fig. 7.1 Fig. 7.2 Fig. 7.3 Fig. 7.4 Fig. 7.5 Fig. 7.6 Fig. 7.7 Fig. 7.8 Fig. 7.9 Fig. 7.10

Fig. 7.1 Fig. 7.2 Fig. 7.3 Fig. 7.4 Fig. 7.5 Fig. 7.6 Fig. 7.7 Fig. 7.8 Fig. 7.9 Fig. 7.10 CHAPTER 7 CLASSES: PART II 1 Illustrations List (Main Page) Fig. 7.1 Fig. 7.2 Fig. 7.3 Fig. 7.4 Fig. 7.5 Fig. 7.6 Fig. 7.7 Fig. 7.8 Fig. 7.9 Fig. 7.10 Using a Time class with const objects and const member

More information

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

Deitel Dive-Into Series: Dive-Into Cygwin and GNU C++ 1 Deitel Dive-Into Series: Dive-Into Cygwin and GNU C++ Objectives To be able to use Cygwin, a UNIX simulator. To be able to use a text editor to create C++ source files To be able to use GCC to compile

More information

Angela Chih-Wei Tang Visual Communications Lab Department of Communication Engineering National Central University JhongLi, Taiwan.

Angela Chih-Wei Tang Visual Communications Lab Department of Communication Engineering National Central University JhongLi, Taiwan. C++ Classes: Part II Angela Chih-Wei Tang Visual Communications Lab Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 17.2 const (Constant) Objects and

More information

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2

More information

Chapter 17 - C++ Classes: Part II

Chapter 17 - C++ Classes: Part II Chapter 17 - C++ Classes: Part II 17.1 Introduction 17.2 const (Constant) Objects and const Member Functions 17.3 Composition: Objects as Members of Classes 17.4 friend Functions and friend Classes 17.5

More information

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

Preview 9/20/2017. Object Oriented Programing with C++ Object Oriented Programing with C++ Object Oriented Programing with C++ Preview Object Oriented Programming with C++ Class Members Inline Functions vs. Regular Functions Constructors & Destructors Initializing class Objects with Constructors C++ Programming Language C Programming

More information

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Chapter 17 - C++ Classes: Part II 17.1 Introduction 17.2 const (Constant) Objects and const Member Functions 17.3 Composition: Objects as Members of Classes 17.4 friend

More information

Object Oriented Design

Object Oriented Design Object Oriented Design Chapter 9 Initializing a non-static data member in the class definition is a syntax error 1 9.2 Time Class Case Study In Fig. 9.1, the class definition is enclosed in the following

More information

Preview 11/1/2017. Constant Objects and Member Functions. Constant Objects and Member Functions. Constant Objects and Member Functions

Preview 11/1/2017. Constant Objects and Member Functions. Constant Objects and Member Functions. Constant Objects and Member Functions Preview Constant Objects and Constant Functions Composition: Objects as Members of a Class Friend functions The use of Friend Functions Some objects need to be modifiable and some do not. A programmer

More information

! 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 Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Spring 2013 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform

More information

! 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 Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Fall 2012 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform

More information

! 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 Ch 13: Introduction to Classes 13.1 Procedural Programming Data is stored in variables CS 2308 Spring 2014 Jill Seaman - Perhaps using arrays and structs. Program is a collection of functions that perform

More information

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

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 to Classes 13.2 The Class Unit 4 Chapter 13 CS 2308 Fall 2016 Jill Seaman 1 l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains

More information

! 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 Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Spring 2015 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform

More information

! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class.

! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class. Classes and Objects Week 5 Gaddis:.2-.12 14.3-14.4 CS 5301 Fall 2016 Jill Seaman The Class! A class in C++ is similar to a structure.! A class contains members: - variables AND - functions (often called

More information

! 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 Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Fall 2013 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform

More information

l A class in C++ is similar to a structure. l A class contains members: - variables AND - public: accessible outside the class.

l A class in C++ is similar to a structure. l A class contains members: - variables AND - public: accessible outside the class. Classes and Objects Week 5 Gaddis:.2-.12 14.3-14.4 CS 5301 Spring 2018 Jill Seaman The Class l A class in C++ is similar to a structure. l A class contains members: - variables AND - functions (often called

More information

The Class. Classes and Objects. Example class: Time class declaration with functions defined inline. Using Time class in a driver.

The Class. Classes and Objects. Example class: Time class declaration with functions defined inline. Using Time class in a driver. Classes and Objects Week 5 Gaddis:.2-.12 14.3-14.4 CS 5301 Fall 2014 Jill Seaman The Class A class in C++ is similar to a structure. A class contains members: - variables AND - functions (often called

More information

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

UEE1302 (1102) F10 Introduction to Computers and Programming (I) Computational Intelligence on Automation Lab @ NCTU UEE1302 (1102) F10 Introduction to Computers and Programming (I) Programming Lecture 10 Pointers & Dynamic Arrays (I) Learning Objectives Pointers Data

More information

! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class.

! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class. Classes and Objects Week 5 Gaddis:.2-.12 14.3-14.4 CS 5301 Spring 2015 Jill Seaman The Class! A class in C++ is similar to a structure.! A class contains members: - variables AND - functions (often called

More information

Classes: A Deeper Look, Part 1

Classes: A Deeper Look, Part 1 9 Classes: A Deeper Look, Part 1 OBJECTIVES In this chapter you will learn: How to use a preprocessor wrapper to prevent multiple definition errors caused by including more than one copy of a header file

More information

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

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 to Classes 13.2 The Class Unit 4 Chapter 13 CS 2308 Spring 2017 Jill Seaman 1 l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains

More information

Lecture 5. Function Pointers

Lecture 5. Function Pointers Lecture 5 Pointers to functions Complicated declarations Allocating and deallocating memory Classes const member functions Constructors and destructor this pointer static members Templates Lec 5 Programming

More information

Classes and Data Abstraction. Topic 5

Classes and Data Abstraction. Topic 5 Classes and Data Abstraction Topic 5 Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes The data and functions of a class

More information

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

Classes and Objects. Types and Classes. Example. Object Oriented Programming Classes and Objects Types and Classes Chapter 6 Object Oriented program development. Read this Chapter 7 Classes Read this Chapter 8 More About Classes Some sections will be assigned later Chapter 9 Inheritance.

More information

Object-Based Programming (Deitel chapter 8)

Object-Based Programming (Deitel chapter 8) Object-Based Programming (Deitel chapter 8) 1 Plan 2 Introduction Implementing a Time Abstract Data Type with a Class Class Scope Controlling Access to Members Referring to the Current Object s Members

More information

Object Oriented Design

Object Oriented Design Object Oriented Design Lecture 3: Introduction to C++ (Continue) Examples using declarations that eliminate the need to repeat the std:: prefix 1 Examples using namespace std; enables a program to use

More information

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

Chapter 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 information

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

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. 1 C How to Program, 6/e 1 Structures : Aggregate data types are built using elements of other types struct Time { int hour; int minute; Members of the same structure must have unique names. Two different

More information

Introduction to C++ Introduction to C++ 1

Introduction to C++ Introduction to C++ 1 1 What Is C++? (Mostly) an extension of C to include: Classes Templates Inheritance and Multiple Inheritance Function and Operator Overloading New (and better) Standard Library References and Reference

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

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

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples. Outline Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples. 1 Arrays I Array One type of data structures. Consecutive group of memory locations

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

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

G205 Fundamentals of Computer Engineering. CLASS 3, Wed. Sept Stefano Basagni Fall 2004 M-W, 1:30pm-3:10pm G205 Fundamentals of Computer Engineering CLASS 3, Wed. Sept. 15 2004 Stefano Basagni Fall 2004 M-W, 1:30pm-3:10pm Function Calls A function is called via its name Actual parameters are passed for the

More information

In this chapter, you will learn about: Pointers. Dynamic Arrays. Introduction Computer Science 1 CS 23021

In this chapter, you will learn about: Pointers. Dynamic Arrays. Introduction Computer Science 1 CS 23021 Chapter 9 In this chapter, you will learn about: Pointers Dynamic Arrays Address A pointer is the memory address of a variable 1022 1023 x Recall, Computer memory is divided into cells (or bytes) 1024

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Storage Classes Scope Rules Functions with Empty Parameter Lists Inline Functions References and Reference Parameters Default Arguments Unary Scope Resolution Operator Function

More information

Chapter 9. Pointers and Dynamic Arrays

Chapter 9. Pointers and Dynamic Arrays Chapter 9 Pointers and Dynamic Arrays Overview 9.1 Pointers 9.2 Dynamic Arrays Slide 9-2 9.1 Pointers Pointers n A pointer is the memory address of a variable n Memory addresses can be used as names for

More information

1 OBJECT-BASED PROGRAMMING CHAPTER 8

1 OBJECT-BASED PROGRAMMING CHAPTER 8 1 OBJECT-BASED PROGRAMMING CHAPTER 8 8 Object-Based Programming 1 // Fig. 8.1: Time1.java 2 // Time1 class definition 3 import java.text.decimalformat; // used for number formatting 4 5 // This class maintains

More information

Chapter Overview. Pointers and Dynamic Arrays. Pointers. Pointers. Declaring Pointers. Pointers Tell Where To Find A Variable. 9.

Chapter Overview. Pointers and Dynamic Arrays. Pointers. Pointers. Declaring Pointers. Pointers Tell Where To Find A Variable. 9. Chapter 9 Pointers and Dynamic Arrays Overview 9.1 Pointers 9.2 Dynamic Arrays Copyright 2011 Pearson Addison-Wesley. All rights reserved. Slide Revised by Zuoliu Ding at Fullerton College, Fall 2011 Slide

More information

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

Cpt 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 information

Introduction to C++ Systems Programming

Introduction 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 information

Lecture 18 Tao Wang 1

Lecture 18 Tao Wang 1 Lecture 18 Tao Wang 1 Abstract Data Types in C++ (Classes) A procedural program consists of one or more algorithms that have been written in computerreadable language Input and display of program output

More information

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

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 12: Classes and Data Abstraction C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 12: Classes and Data Abstraction Objectives In this chapter, you will: Learn about classes Learn about private, protected,

More information

Computer Programming C++ Classes and Objects 6 th Lecture

Computer Programming C++ Classes and Objects 6 th Lecture Computer Programming C++ Classes and Objects 6 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2015 Eom, Hyeonsang All Rights Reserved Outline

More information

Pointers and Dynamic Arrays

Pointers and Dynamic Arrays Pointers and Dynamic Arrays Pointers A pointer is the memory address of a variable Memory addresses can be used as names for variables If a variable is stored in three memory locations, the address of

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

III. Classes (Chap. 3)

III. 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 information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

Fast Introduction to Object Oriented Programming and C++

Fast 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 information

AN OVERVIEW OF C++ 1

AN 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 information

Chapter 18 - C++ Operator Overloading

Chapter 18 - C++ Operator Overloading Chapter 18 - C++ Operator Overloading Outline 18.1 Introduction 18.2 Fundamentals of Operator Overloading 18.3 Restrictions on Operator Overloading 18.4 Operator Functions as Class Members vs. as friend

More information

Object-Based Programming

Object-Based Programming Object-Based Programming 8.1 Introduction 8.2 Implementing a Time Abstract Data Type with a Class 8.3 Class Scope 8.4 Controlling Access to Members 8.5 Creating Packages 8.6 Initializing Class Objects:

More information

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty! Chapter 6 - Functions return type void or a valid data type ( int, double, char, etc) name parameter list void or a list of parameters separated by commas body return keyword required if function returns

More information

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

C++ As A Better C Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan. C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2013 Fall Outline 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.5

More information

Chapter 7: Classes Part II

Chapter 7: Classes Part II 1 Chapter 7: Classes Part II 7.1 Introduction 7.2 const (Constant) Objects and const Member Functions 7.3 Composition: Objects a s Members of Cla sses 7.4 friend Func tions a nd friend Cla sse s 7.5 Using

More information

CS304 Object Oriented Programming Final Term

CS304 Object Oriented Programming Final Term 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes? Generalization (pg 29) Sub-typing

More information

Operator Overloading in C++ Systems Programming

Operator Overloading in C++ Systems Programming Operator Overloading in C++ Systems Programming Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. Global Functions Overloading

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++ CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many

More information

Chapter 10 Introduction to Classes

Chapter 10 Introduction to Classes C++ for Engineers and Scientists Third Edition Chapter 10 Introduction to Classes CSc 10200! Introduction to Computing Lecture 20-21 Edgardo Molina Fall 2013 City College of New York 2 Objectives In this

More information

Homework #3 CS2255 Fall 2012

Homework #3 CS2255 Fall 2012 Homework #3 CS2255 Fall 2012 MULTIPLE CHOICE 1. The, also known as the address operator, returns the memory address of a variable. a. asterisk ( * ) b. ampersand ( & ) c. percent sign (%) d. exclamation

More information

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types Chapter 4 - Arrays 1 4.1 Introduction 4.2 Arrays 4.3 Declaring Arrays 4.4 Examples Using Arrays 4.5 Passing Arrays to Functions 4.6 Sorting Arrays 4.7 Case Study: Computing Mean, Median and Mode Using

More information

EL2310 Scientific Programming

EL2310 Scientific Programming (pronobis@kth.se) Overview Overview Wrap Up Introduction to Object Oriented Paradigm More on and Members Operator Overloading Last time Intro to C++ Differences between C and C++ Intro to OOP Today Object

More information

Constructor - example

Constructor - example Constructors A constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is same as the class name. The constructor is invoked whenever

More information

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

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

More information

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public

More information

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual

More information

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Introduction 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 information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010 CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)

More information

G52CPP C++ Programming Lecture 13

G52CPP C++ Programming Lecture 13 G52CPP C++ Programming Lecture 13 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture Function pointers Arrays of function pointers Virtual and non-virtual functions vtable and

More information

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in: CS 215 Fundamentals of Programming II C++ Programming Style Guideline Most of a programmer's efforts are aimed at the development of correct and efficient programs. But the readability of programs is also

More information

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) Chapter - Arrays 1.1 Introduction 2.1 Introduction.2 Arrays.3 Declaring Arrays. Examples Using Arrays.5 Passing Arrays to Functions.6 Sorting Arrays. Case Study: Computing Mean, Median and Mode Using Arrays.8

More information

Operator Overloading

Operator Overloading Operator Overloading Introduction Operator overloading Enabling C++ s operators to work with class objects Using traditional operators with user-defined objects Requires great care; when overloading is

More information

How to engineer a class to separate its interface from its implementation and encourage reuse.

How to engineer a class to separate its interface from its implementation and encourage reuse. 1 3 Introduction to Classes and Objects 2 OBJECTIVES In this chapter you ll learn: What classes, objects, member functions and data members are. How to define a class and use it to create an object. How

More information