CSCE 110 PROGRAMMING FUNDAMENTALS WITH C Prof Amr

  • Slides: 52
Download presentation
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 14. User Defined

CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 14. User Defined Classes Prof. amr Goneid, AUC 1

User Defined Classes Prof. amr Goneid, AUC 2

User Defined Classes Prof. amr Goneid, AUC 2

User Defined Classes n n n n n OOP & Classes Data Encapsulation, Classes

User Defined Classes n n n n n OOP & Classes Data Encapsulation, Classes and objects Class Definition: Private & Public Members Constructors & Destructors Data and Function Members Accessors & Mutators Polymorphism and Overloading Example: Rational Numbers Class Example: Simple String Class Prof. amr Goneid, AUC 3

1. OOP and Classes n Object-Oriented Programming (OOP) focuses on creating ADT’s called “Classes”

1. OOP and Classes n Object-Oriented Programming (OOP) focuses on creating ADT’s called “Classes” that identify “objects” and how they work together. n A class contains “data members” + “function members” in one object. n A member function tells an object to “operate on itself” in some way. n Objects are “self-contained”, carrying their own operations. Prof. amr Goneid, AUC 4

2. Data Encapsulation, Classes and Objects n A Class of objects is a user-defined

2. Data Encapsulation, Classes and Objects n A Class of objects is a user-defined Abstract Data Type (ADT) n An object is an instance of the class n Once a class is defined, an object can be declared to be of that type. For example, we have encountered the string class before. Since it has been defined, we can declare: string message; So, now message is an object of that class n Classes can be used by more than one program. Prof. amr Goneid, AUC 5

Sharing Classes Class Program Standard Classes Prof. amr Goneid, AUC Class Program User Classes

Sharing Classes Class Program Standard Classes Prof. amr Goneid, AUC Class Program User Classes 6

Classes & Encapsulation n C++ classes are similar to structs, with the main difference

Classes & Encapsulation n C++ classes are similar to structs, with the main difference being that classes can have member functions, or methods, as well as variables, or data members in their definitions. n Combining data and operations (methods) together in an object is called encapsulation. n An object of a class can operate on itself by the methods or member functions of that class. e. g. , an object of class string can operate by: . find . length . at Prof. amr Goneid, AUC . erase etc 7

3. Class Definition: Private & Public Members § Classes use the technique of information

3. Class Definition: Private & Public Members § Classes use the technique of information hiding to avoid incorrect use of the class. This is done by creating two areas: a public area, and a private area public: Member Functions Outside World private: Data members Prof. amr Goneid, AUC 8

Private & Public Members External world has no access to the private area. Users

Private & Public Members External world has no access to the private area. Users are allowed to operate on the objects of the class only via public member functions. All member functions of a class have automatic access to all of the data members of that class. Once we make a member variable a private member variable, there is then no way to change its value except by using one of the member functions. Prof. amr Goneid, AUC 9

Class Definition A class definition contains only the prototype for its member functions and

Class Definition A class definition contains only the prototype for its member functions and the definitions of the data members. It is declared in a class header file (. h) The implementations for the member functions are given elsewhere, in a class implementation file (. cpp) not in the header file. These two files form the Class Library. Prof. amr Goneid, AUC 10

General Format of a Class Declaration (in Header File) class Class. Name { public:

General Format of a Class Declaration (in Header File) class Class. Name { public: function prototypes of methods and data members that are public and can be used by statements outside the class definition. private: prototypes of functions and type definitions and variable declarations of data members that are private and can be used only by statements inside the class definition. }; // a semicolon must appear here Prof. amr Goneid, AUC 11

Class Library Files n The name of the header file is the class name

Class Library Files n The name of the header file is the class name followed by “. h “ , e. g. Class. Name. h n The name of the implementation file matches that of the header file with an extension of “. cpp”, e. g. Class. Name. cpp n Application programs using the class are called “client programs”. n These programs must include: #include “Class. Name. h” #include “Classname. cpp” Prof. amr Goneid, AUC 12

4. Constructors and Destructors Two special functions in the public part with the same

4. Constructors and Destructors Two special functions in the public part with the same name as the class: n The constructor is used to create and initialize objects declared to be of that class n There could be more than one constructor to allow for different ways of initializing objects. n The destructor is used to remove the objects (specially when the data is allocated dynamically). Only one destructor is allowed. Prof. amr Goneid, AUC 13

5. Data & Function Members: Example Header File //File: Time. h Time Class Header

5. Data & Function Members: Example Header File //File: Time. h Time Class Header File #ifndef TIME_H // used to avoid multiple definitions #define TIME_H // not part of the class Time { public: Time(); // constructor, a must ~Time(); // destructor Function cannot change // Function prototypes private members void set. Time (int, int); void display. Time (); const private: int hour, minute, second; }; // a semicolon must appear here #endif // TIME_H #include “Time. cpp" Prof. amr Goneid, AUC 14

Implementing Member Functions n A member function is implemented in the implementation file (.

Implementing Member Functions n A member function is implemented in the implementation file (. cpp). The format is: <type> <class name> : : <function name> (param list) {. . function body. . } The Scope resolution operator: : : prefix for each member function Informs the compiler that the function is a member of the class Prof. amr Goneid, AUC 15

Example Implementation File //File: Time. cpp Time Class Implementation File #include <iostream> using namespace

Example Implementation File //File: Time. cpp Time Class Implementation File #include <iostream> using namespace std; Time : : Time() { hour = minute = second = 0; } Time: : ~Time() { } // do nothing void Time : : set. Time(int h, int m, int s) { hour = (h >= 0 && h < 24) ? h : 0; minute = (m >= 0 && m < 60) ? m : 0; second = (s >= 0 && s < 60) ? s : 0; } void Time : : display. Time() const { cout << hour << “: “ << minute << “: “ << second << endl; } Prof. amr Goneid, AUC 16

Objects n Object: a particular instance of the class. n To declare an object

Objects n Object: a particular instance of the class. n To declare an object in a client program: The same way we declare a variable but with the type = class name, e. g. Time t 1; Time T[20]; This will also invoke the constructor. n The Dot Operator allows an object to access its public members, e. g. t 1. display. Time(); Prof. amr Goneid, AUC 17

Example of Application (Client) File //File: Time. Appl. cpp Time Class Application File #include

Example of Application (Client) File //File: Time. Appl. cpp Time Class Application File #include “Time. h“ #include <iostream> using namespace std; int main() { Time t 1 , t 2; cout << “Start Time is: “; t 1. display. Time ( ); t 2. set. Time (5, 10, 30); cout << “End Time is: “; t 2. display. Time ( ); return 0; } Prof. amr Goneid, AUC 18

Remarks n Every class should have a default constructor (without parameters). n The default

Remarks n Every class should have a default constructor (without parameters). n The default constructor may also be implemented as: Time : : Time( ) : hour(0), minute(0), second(0) {} member initializers When used in the application program as: Time t 1; then t 1. hour, t 1. minute and t 1. second will be set initially to zero Prof. amr Goneid, AUC 19

Remarks n An explicit value constructor may also be added and defined as: Time(

Remarks n An explicit value constructor may also be added and defined as: Time( int , int); and is implemented as: Time : : Time( int h, int m, int s) { hour = h; minute = m; second = s; } We can use it in the application to initialize an object: Time t 1(7, 45, 0); n const functions cannot modify private data members Prof. amr Goneid, AUC 20

6. Accessors and Mutators n It is possible to extract a private data member

6. Accessors and Mutators n It is possible to extract a private data member using an accessor function. For example, to access “hour”: int get. Hour( ) const; // Prototype int Time: : get. Hour( ) const { return hour; } Time t 1; int h = t 1. get. Hour( ); // function definition // invoking the function n A mutator member function (like set. Time( )) will be able to change the private data members. Prof. amr Goneid, AUC 21

7. Polymorphism & Overloading n Defining several functions with the same name is called

7. Polymorphism & Overloading n Defining several functions with the same name is called function overloading n The presence of more than one constructor for the class is an example of function overloading. n Polymorphism is what allows functions with the same name to do different things based on its arguments Prof. amr Goneid, AUC 22

8. Example: ADT rational Abstraction: A rational number (fraction) is a rational representation of

8. Example: ADT rational Abstraction: A rational number (fraction) is a rational representation of two integers (x, y). Elements or Members: A numerator (x) and a denominator (y), both are integers. (y) cannot be zero Relationship: The representation is equivalent to x / y Prof. amr Goneid, AUC 23

ADT rational (continued) Fundamental Operations: n Read a fraction from keyboard n Display a

ADT rational (continued) Fundamental Operations: n Read a fraction from keyboard n Display a fraction on the screen n Add Fractions f = f 1 + f 2 (e. g. ½ + ¼ = ¾) n Subtract Fractions f = f 1 – f 2 (e. g. ½ - 1/3 = 1/6) n Multiply Fractions f = f 1 * f 2 (e. g. ½ * ¾ = 3/8) n Divide Fractions f = f 1 / f 2 (e. g. 1/5 / ¼ = 4/5) n Reduce Fractions (e. g. 2/6 = 1/3) Prof. amr Goneid, AUC 24

Implementing a rational Class We will have 3 files: n “rational. h” to contain

Implementing a rational Class We will have 3 files: n “rational. h” to contain the class definition. n “rational. cpp” to contain the implementation of the member functions. n “Rational. Test. cpp” an application file to test the class. Prof. amr Goneid, AUC 25

The Header File: rational. h // Rational class definition #ifndef RATIONAL_H // used to

The Header File: rational. h // Rational class definition #ifndef RATIONAL_H // used to avoid multiple definitions #define RATIONAL_H // not part of the class rational { public: // Member functions // Constructors rational(); // Default Constructor rational(int); // Initialize numerator with denom = 1 rational(int, int); // Initialize both numerator and denom. Prof. amr Goneid, AUC 26

The Header File: rational. h (cont. ) void set. Num(int); // Set numerator and

The Header File: rational. h (cont. ) void set. Num(int); // Set numerator and denominator void set. Denom(int); rational multiply(const rational &f); // Multiply fractions rational divide(const rational &f); // Divide fractions rational add(const rational &f); // Add Fractions rational subtract(const rational &f); // Subtract Fractions void read. Rational(); // Read a fraction void display. Rational() const; // Display a fraction rational reduce() const; // Reduce fraction // Accessors int get. Num() const; int get. Denom() const; Prof. amr Goneid, AUC 27

The Header File: rational. h (cont. ) // Operator Style // Add object to

The Header File: rational. h (cont. ) // Operator Style // Add object to parameter rational operator + (const rational &); // Test equality of object and parameter bool operator == (const rational &); private: // Data members (attributes) int num; // private data field int denom; // private data field }; // Note -- a class definition MUST end with a semicolon #endif // RATIONAL_H #include "rational. cpp" Prof. amr Goneid, AUC 28

The Implementation File: rational. cpp // File: Rational. cpp // Rational class implementation #include

The Implementation File: rational. cpp // File: Rational. cpp // Rational class implementation #include <iostream> using namespace std; // Member functions // Constructors rational: : rational() { num = 0; denom = 0; } // Default Costructor rational: : rational(int n) { num = n; denom = 1; } // Class Constructor rational: : rational(int n, int d) { num = n; denom = d; } // Class Constructor Prof. amr Goneid, AUC 29

The Implementation File: rational. cpp // Set numerator and denominator void rational: : set.

The Implementation File: rational. cpp // Set numerator and denominator void rational: : set. Num(int n) { num = n; } void rational: : set. Denom(int d) { denom = d; } // Multiply fractions rational: : multiply(const rational &f) { rational temp(num * f. num, denom * f. denom); return temp; } // Divide fractions rational: : divide(const rational &f) { rational temp(num * f. denom, denom * f. num); return temp; } Prof. amr Goneid, AUC 30

The Implementation File: rational. cpp // Add fractions rational: : add(const rational &f) {

The Implementation File: rational. cpp // Add fractions rational: : add(const rational &f) { rational temp(num * f. denom + f. num * denom, denom * f. denom); return temp; } // Subtract Fractions rational: : subtract(const rational &f) { rational temp(num * f. denom - f. num * denom, denom * f. denom); return temp; } Prof. amr Goneid, AUC 31

The Implementation File: rational. cpp // Read a fraction void rational: : read. Rational()

The Implementation File: rational. cpp // Read a fraction void rational: : read. Rational() { char slash; // storage for / do { cout << "Enter numerator / denominator: "; cin >> num >> slash >> denom; } while (slash != '/'); } // Display a fraction void rational: : display. Rational() const { cout << num << '/' << denom; } Prof. amr Goneid, AUC 32

The Implementation File: rational. cpp // Reduce rational: : reduce() const { int n,

The Implementation File: rational. cpp // Reduce rational: : reduce() const { int n, m, rem, gcd; // Get the two integers n = abs(num); m = abs(denom); while (n > 0) { rem = m % n; m = n; n = rem; } gcd = m; rational g (num/gcd, denom/gcd); return g; } Prof. amr Goneid, AUC 33

The Implementation File: rational. cpp // Accessors int rational: : get. Num() const {

The Implementation File: rational. cpp // Accessors int rational: : get. Num() const { return num; } int rational: : get. Denom() const { return denom; } // Operator-Like rational: : operator + (const rational &f 2) { rational temp (num * f 2. denom + f 2. num * denom, denom * f 2. denom); return temp; } bool rational: : operator == (const rational &f) { return (num == f. num && denom == f. denom); } Prof. amr Goneid, AUC 34

Remarks n It is possible to create a temporary class object within a member

Remarks n It is possible to create a temporary class object within a member function and initialize it using a constructor, e. g. rational: : multiply(const rational &f) { rational temp (num * f. num, denom * f. denom); return temp; } n A regular C++ operator can be “overloaded” to perform a different action on class objects. A member function can be defined to do this. If is an operator, the prototype will be: <type> operator (parameter); e. g. bool operator == (const rational &); Prof. amr Goneid, AUC 35

Remarks n The definition will be: <type> <Class. Name>: : operator (parameter); e. g.

Remarks n The definition will be: <type> <Class. Name>: : operator (parameter); e. g. bool rational: : operator == (const rational &f) { return (num == f. num && denom == f. denom); } For example: rational a , b; An expression of the form (a == b) will be evaluated as: (a. num == b. num) && (a. denom == b. denom) Prof. amr Goneid, AUC 36

The Application File: Rational. Test. cpp // Tests the rational class #include <iostream> #include

The Application File: Rational. Test. cpp // Tests the rational class #include <iostream> #include "rational. h“ using namespace std; int main() { rational f 1, f 2; rational f 3; // Read two rational numbers cout << "Enter 1 st fraction: " << endl; f 1. read. Rational(); cout << "Enter 2 nd fraction: " << endl; f 2. read. Rational(); Prof. amr Goneid, AUC 37

The Application File: Rational. Test. cpp // Fraction Arithmetic f 3 = f 1.

The Application File: Rational. Test. cpp // Fraction Arithmetic f 3 = f 1. multiply(f 2); f 1. display. Rational(); cout << " * "; f 2. display. Rational(); cout << " = "; f 3 = f 3. reduce(); f 3. display. Rational(); cout << endl; f 3 = f 1. divide(f 2); f 1. display. Rational(); cout << " / "; f 2. display. Rational(); cout << " = "; f 3 = f 3. reduce(); f 3. display. Rational(); cout << endl; Prof. amr Goneid, AUC 38

The Application File: Rational. Test. cpp f 3 = f 1. add(f 2); f

The Application File: Rational. Test. cpp f 3 = f 1. add(f 2); f 1. display. Rational(); cout << " + "; f 2. display. Rational(); cout << " = "; f 3 = f 3. reduce(); f 3. display. Rational(); cout << endl; f 3 = f 1 + f 2; // uses operator “+” for addition f 1. display. Rational(); cout << " + "; f 2. display. Rational(); cout << " = "; f 3 = f 3. reduce(); f 3. display. Rational(); cout << endl; Prof. amr Goneid, AUC 39

The Application File: Rational. Test. cpp f 3 = f 1. subtract(f 2); f

The Application File: Rational. Test. cpp f 3 = f 1. subtract(f 2); f 1. display. Rational(); cout << " - "; f 2. display. Rational(); cout << " = "; f 3 = f 3. reduce(); f 3. display. Rational(); cout << endl; return 0; } Prof. amr Goneid, AUC 40

Sample Run of Rational. Test. cpp Enter 1 st fraction: Enter numerator / denominator:

Sample Run of Rational. Test. cpp Enter 1 st fraction: Enter numerator / denominator: 2/6 Enter 2 nd fraction: Enter numerator / denominator: 3/8 2/6 * 3/8 = 6/48 = 1/8 2/6 / 3/8 = 16/18 = 8/9 2/6 + 3/8 = 34/48 = 17/24 2/6 - 3/8 = -2/48 = -1/24 Press any key to continue Prof. amr Goneid, AUC 41

9. Example: Simple String Class Here we build a simple string class to do

9. Example: Simple String Class Here we build a simple string class to do few tasks on our own string objects, e. g. read, write, get the character at a given location, etc. We implement the string as a dynamic array of characters. We will have 3 files: n “simple. String. h” to contain the class definition. n “simple. String. cpp” to contain the implementation of the member functions. n “simple. String. Test. cpp” an application file to test the class. Prof. amr Goneid, AUC 42

The Header File: simple. String. h // File simple. String. h // Simple string

The Header File: simple. String. h // File simple. String. h // Simple string class definition #ifndef SIMPLESTRING_H #define SIMPLESTRING_H class simple. String { public: // Member Functions // Constructors simple. String(); simple. String(int ); // Destructor ~simple. String(); Prof. amr Goneid, AUC 43

The Header File: simple. String. h // Function Prototype definition // Read a simple

The Header File: simple. String. h // Function Prototype definition // Read a simple string void read. String(); // Display a simple string void write. String() const; // Retrieve the character at a specified position // Returns the character if position is out of bounds char at(int) const; // Return the string length int get. Length() const; // Return the string capacity int get. Capacity() const; // Get the contents into an array void get. Contents(char[ ]) const; Prof. amr Goneid, AUC 44

The Header File: simple. String. h private: // Data members (attributes) // maximum size

The Header File: simple. String. h private: // Data members (attributes) // maximum size int capacity; // pointer to a dynamic storage array char *s; // current length int length; }; #endif //SIMPLESTRING_H #include "simple. String. cpp" Prof. amr Goneid, AUC 45

The Implementation File: simple. String. cpp // File: simplestring. cpp // Simple string class

The Implementation File: simple. String. cpp // File: simplestring. cpp // Simple string class implementation #include <iostream> using namespace std; // Member Functions. . . // default constructor, capacity = 255 simple. String: : simple. String() { s = new char[255]; capacity = 255; length = 0; } // Constructor with argument, capacity is m. Val simple. String: : simple. String(int m. Val) { s = new char [m. Val]; capacity = m. Val; length = 0; } // Class Destructor simple. String: : ~simple. String() { delete [ ] s; } Prof. amr Goneid, AUC 46

The Implementation File: simple. String. cpp // Read a simple string void simple. String:

The Implementation File: simple. String. cpp // Read a simple string void simple. String: : read. String() { char next; int pos = 0; cin. get(next); while ((next != 'n') && (pos < capacity)) { // Insert next in array contents s[pos] = next; pos++; cin. get(next); } length = pos; } Prof. amr Goneid, AUC 47

The Implementation File: simple. String. cpp // Write a simple string void simple. String:

The Implementation File: simple. String. cpp // Write a simple string void simple. String: : write. String() const { for (int pos = 0; pos < length; pos++) cout << s[pos]; } // Character at (pos). Returns if position is out of bounds char simple. String: : at(int pos) const { const char nullcharacter = ''; if ((pos < 0) || (pos >= length)) { cerr << "position " <<pos << " not defined. " << endl; return nullcharacter; } else return s[pos]; } Prof. amr Goneid, AUC 48

The Implementation File: simple. String. cpp // Return the string length int simple. String:

The Implementation File: simple. String. cpp // Return the string length int simple. String: : get. Length() const { return length; } // Return the string capacity int simple. String: : get. Capacity() const { return capacity; } // Get the contents into an array void simple. String: : get. Contents(char str[ ]) const { for (int i = 0; i < length; i++) str[i] = s[i]; } Prof. amr Goneid, AUC 49

The Application File: simple. String. Test. cpp // Tests the simple string class #include

The Application File: simple. String. Test. cpp // Tests the simple string class #include "simple. String. h“ #include <iostream> using namespace std; int main() { simple. String S 1; simple. String S 2(20); cout << S 1. get. Capacity() <<" "<<S 1. get. Length() << endl; cout << S 2. get. Capacity() <<" "<<S 2. get. Length() << endl; Prof. amr Goneid, AUC 50

The Application File: simple. String. Test. cpp // Read in a string. cout <<

The Application File: simple. String. Test. cpp // Read in a string. cout << "Enter a string and press RETURN: "; S 1. read. String(); // Display the string just read. cout << "The string read was: "; S 1. write. String(); cout << endl; // Display each character on a separate line. cout << "The characters in the string follow: " << endl; for (int pos = 0; pos < S 1. get. Length(); pos++) cout << S 1. at(pos) << endl; return 0; } Prof. amr Goneid, AUC 51

Sample Run of simple. String. Test. cpp 255 0 20 0 Enter a string

Sample Run of simple. String. Test. cpp 255 0 20 0 Enter a string and press RETURN: User Classes The string read was: User Classes The characters in the string follow: U s e r C l a s s e s Press any key to continue Prof. amr Goneid, AUC 52