1 / 65

Programming Principles II

Andreas Savva. Programming Principles II. Lecture Notes 6.1 Object Oriented Programming. Objects. An object is simply a self-contained entity that has an existence independent of other entities. a pencil a book a car a basketball a watch a house. Objects and Classes.

gyda
Download Presentation

Programming Principles II

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Andreas Savva Programming Principles II Lecture Notes 6.1 Object Oriented Programming

  2. Objects • An object is simply a self-contained entity that has an existence independent of other entities. • a pencil • a book • a car • a basketball • a watch • a house

  3. Objects and Classes • A class can be regarded as the general form of an object: • The Tower Bridge in London belongs to the class of bridges; • The Bran Castle (Dracula’s castle in Rumania) belongs to the class of castles; • Barack Obama belongs to the class of USA presidents or to the class of humans; • Lionel Messi belongs to the class of football players; • The Land Rover Defender 90 TDI 4WD with RegNo CAA236 belongs to the class of cars;

  4. Attributes and Operations • Properties of the class Employ: • Attributes and operations are called members of a class. • Attributes are called data members. • Operations are called member functions.

  5. Abstract Data Types (ADT) • Data cannot be accessed directly. • Data can only be accessed indirectly via the subprograms (member functions) associated with the data. • Thus, the class contains: • The data structure. • Subprograms to access and/or modify the data structure.

  6. Information Hiding • A client (user program) does not need to know how the data are actually stored or how the methods are programmed. This important programming strategy is called information hiding. • Data members and member functions (methods) available to a client are called public. • Private variables and member functions (functions) may be used in the implementation of the class, but are not available to a client. Methods of a class are public Functions in a class are private

  7. Example – Abstract Data Type • Main activities for operating a car are: • steering, accelerating, braking • The design of a car can be viewed as an ADT with operations: • steer, accelerate, brake • Two cars may implement these operations in different ways. • Most drivers can operate any car since the ADT presents a uniform method of operation.

  8. C++ Class Declaration class Name { public: // Public members go here (internal to the class) private: // Private members go here (visible from outside) };

  9. The Class Time classTime{ public: voidsetTime(int, int, int); void print24hour(); void print12hour(); private: void twoDigits(int); int hour; int minute; int second; };

  10. Member Functions void Time::setTime(int h, int m, int s) { hour = h; minute = m; second = s; } void Time::print24hour() { twoDigits(hour); cout << ’:’ ; twoDigits(minute); cout << ’:’ ; twoDigits(second); cout << endl; } void Time::print12hour() { int h = (hour % 12 == 0 ? 12 : hour % 12); twoDigits(h); cout << ’:’; twoDigits(minute); cout << ’:’; twoDigits(second); if (hour < 12) cout << ” am” << endl; else cout << ” pm” << endl; } void Time::twoDigits(int n) { if (n < 10) cout << ’0’; cout << n; }

  11. The time in 24 hour format is 16:23:05 The time in 12 hour format is 04:23:05 pm Creating and Using Objects intmain() { Time t; t.setTime(16,23,5); cout << "The time in 24 hour format is: "; t.print24hour(); cout << "The time in 12 hour format is: "; t.print12hour(); cout << endl; return 0; } t hour 16 minute 23 second 5

  12. Defining Functions in the Class class Time { public: voidsetTime(int h, int m, int s) { hour = h; minute = m; second = s; } void print24hour(); void print12hour(); private: void twoDigits(int n) { if (n < 10) cout << ’0’; cout << n; } int hour; int minute; int second; };

  13. Constant Member Functions • In constant member functions we cannot change the values of data members. class Time { public: voidsetTime(int, int, int); void print24hour() const; void print12hour() const; private: void twoDigits(int) const; int hour; int minute; int second; }; void Time::print12hour()const { hour = hour % 12;// ERROR }

  14. Mutable Data Members • Mutable data members can change their values in constant member functions. class Time { public: voidsetTime(int, int, int); void print24hour() const; void print12hour() const; private: void twoDigits(int) const; mutableint hour; int minute; int second; }; void Time::print12hour()const { hour = hour % 12;// CORRECT }

  15. The Class Team classTeam{ public: Team(); // Constructor Team(char*, int = 0, int = 0, int = 0); // Constructor Team(const Team&); // Constructor voidSetname(char*); void Print() const; voidGamePlayed(int, int); ~Team(); // Destructor private: int Points() const; char name[20]; int wins; int draws; int losses; };

  16. Member Functions void Team::Setname(char *s) { strcpy(name, s); } void Team::GamePlayed(intteamGoals, intopponentsGoals) { if (teamGoals > opponentsGoals) wins++; else if (teamGoals == opponentsGoals) draws++; else losses++; } void Team::Print() const { cout << name << " " << Points() << endl; } intTeam::Points() const { return wins * 3 + draws * 1 + losses * 0; }

  17. Constructors • Special functions – have the name of the class • Called automatically when an object of the class is instantiated • Do not return a value (no return type is specified) • Their purpose is to initialize the object’s attributes Team::Team() { strcpy(name, ""); wins = 0; draws = 0; losses = 0; }

  18. Manchester United 3 Liverpool FC 1 Creating and Using Objects int main() { TeamManUtd, Liv; ManUtd.Setname(”Manchester United”); Liv.Setname(”Liverpool FC”); ManUtd.GamePlayed(3, 2); Liv.GamePlayed(2, 2); ManUtd.Print(); Liv.Print(); return 0; }

  19. Overloading the Constructor classTeam{ public: Team(); Team(char *, int= 0, int= 0, int= 0); . . . . . private: . . . . . }; Team::Team() { strcpy(name, ""); wins = 0; draws = 0; losses = 0; } Team::Team(char *s, int w, int d, int l) { strcpy(name, s); wins = w; draws = d; losses = l; } Default values

  20. Manchester United 11 Liverpool FC 7 Arsenal FC 7 Real Madrid 22 Objects int main() { Team ManUtd(”Manchester United”, 3, 2, 1); ManUtd.Print(); Team Liv(”Liverpool FC”, 2); Liv.GamePlayed(2, 2); Liv.Print(); Team Arsenal = Liv; Arsenal.Setname(”Arsenal FC”); Arsenal.Print(); Team *RMadrid = newTeam(”Real Madrid”, 7, 1); RMadrid->Print(); return 0; }

  21. Olympiakos 25 Barcelona FC 24 The Copy Constructor classTeam{ public: Team(); Team(char*, int= 0, int= 0, int= 0); Team(const Team&); . . . . . private: . . . . . }; Team::Team(const Team &tm) { strcpy(name, tm.name); wins = tm.wins; draws = tm.draws; losses = tm.losses; } int main() { Team Barcelona(”Barselona FC”, 8); Team Olympiakos(Barcelona); Olympiakos.Setname(”Olympiakos”); Olympiakos. GamePlayed(2,2); Olympiakos.Print(); Barcelona.Print(); return 0; }

  22. The Destructor • Functions that are called whenever an object is deleted (e.g. goes out of scope) • Its purpose is to perform any necessary cleanup operations • Has no return type • Does not return a value classTeam{ public: . . . . . ~Team(); private: . . . . . }; Team::~Team() { cout << name << ” is deleted\n” ; }

  23. Real Madrid is deleted APOEL is deleted Omonoia is deleted Liverpool FC is deleted Manchester United is deleted Objects and Destructor int main() { TeamManUtd(”Manchester United”, 3, 2, 1); TeamLiv(”Liverpool FC”, 2); Team *RMadrid = new Team(”Real Madrid”, 7, 1); deleteRMadrid; Team Cyprus[2]; Cyprus[0].Setname(”Omonoia”); Cyprus[1].Setname(”APOEL”); return 0; }

  24. The Initializer List • C++ provides an alternative method of initialization, called initializer list. Team::Team(char *s, int w, int d, int l) : wins(w), draws(d), losses(l)// initializer list { strcpy(name, s); // cannot specify initializer for arrays }

  25. Pointers in Classes • If a class object comes into existence dynamically using the new operator, the destructor must be called when this object is destroyed using the delete operator. If a class object comes into existence because it is a local variable in a function, the destructor will be called when the function returns. class Vect { public: Vect(int size = 5) { vectSize = size; theVect = new int[size]; } // . . . ~Vect() { delete [] theVect; } private: intvectSize; int* theVect; };

  26. b a vectSize vectSize 10 5 theVect theVect The Assignment statement { Vect a(10); // a is a vector of size 10 { Vect b; // c is a vector of default size 5 b = a; // assign a to b (DANGER) } // the destructor for b will be executed . . . . . } 10

  27. Copy Constructor & Assignment Operator Vect::Vect(const Vect &a) { vectSize = a.vectSize; theVect = new int[vectSize]; for (inti=0;i<vectSize;i++) theVect[i] = a.theVect[i]; } Vect& Vect::operator=(const Vect &a) { if (this != &a) { delete [] theVect; vectSize = a.vectSize; theVect = new int[vectSize]; for (inti=0;i<vectSize;i++) theVect[i] = a.theVect[i]; } return *this; } • The assignment operator deletes the existing array storage, allocates a new array of the proper size, and copies the elements into this array. The if-statement checks against the possibility of self assignment (a = a). This is done using the “this” keyword. For any class object, this is a pointer to the address of the object.

  28. The Class class Vect { public: Vect(int size = 5) { vectSize = size; theVect = new int[size]; } // . . . ~Vect() { delete [] theVect; } Vect(const Vect&); Vect& operator=(const Vect&); private: intvectSize; int* theVect; };

  29. The String Example class String { public: String(int = 20); String(char*); void Display(); ~String(); private: intlen; char *s; }; String::String(int n) { len = n; s = new char[n]; s[0] = '\0'; } String::String (char *str) { len = strlen(str) + 1; s = new char[len]; strcpy(s,str); } String::~String() { delete [] s; } void String::Display () { cout << s << endl; }

  30. Classes Vs. Structs class: Default is private struct: Default is public struct Time { int hour; int minute; int second; Time(); Time(int, int, int); }; Time::Time() { hour = minute = second = 0; } Time::Time(int h, int m, int s) { hour = h; minute = m; second = s; } class Time { public: int hour; int minute; int second; Time(); Time(int, int, int); }; Time::Time() { hour = minute = second = 0; } Time::Time(int h, int m, int s) { hour = h; minute = m; second = s; }

  31. Overloading Operators • C++ allows operators overloading, such as +, *, +=, and <<. The definition is similar to a function, but in place of a function name we use “operator==”. In general, the == is replaced by the operator to be defined. For binary operators we have two arguments, and for unary operators we have just one. structComplexNum { ComplexNum(float r, float i) { real = r; imaginary = i; } . . . . . friendbool operator==(const ComplexNum&, const ComplexNum&); private: float real; float imaginary; }; bool operator==(const ComplexNum &a, const ComplexNum &b) { return a.real == b.real && a.imaginary == b.imaginary; } void main() { ComplexNum N1(3, 12); // 3 + 12i ComplexNum N2(-2, 1); // -2 + i cout << (N1==N2); // output 0 (false) }

  32. Overloading Operators • Another useful application is defining input and output operators for classes and structures. Here is how to define an output operator for the ComplexNum structure. The type ostream is the system’s output structure. The standard output, cout is of this type. structComplexNum { ComplexNum(float r, float i) { real = r; imaginary = i; } . . . . . friendbool operator==(const ComplexNum&, const ComplexNum&); friendostream& operator<<(ostream&, constComplexNum &); private: float real; float imaginary; }; ostream& operator<<(ostream &out, constComplexNum &a) { out << a.real << (a.imaginary>=0 ? ’+’ : ’-’) << fabs(a.imaginary) << ’i’; return out; } void main() { ComplexNum N1(3, 12); cout << N1; // output 3+12i }

  33. Matrix OperationsA complete program #include <iostream> using namespace std; const int MAX = 10; enum Error_code {fail, success}; classMatrix{ public: Matrix(); void ReadMatrix(); void DisplayMatrix() const; Error_code AddSubtract(char , const Matrix&, const Matrix&); Error_code Multiply(const Matrix&, const Matrix&); private: int row, col; float entry[MAX][MAX]; };

  34. Constructor & ReadMatrix Matrix::Matrix() { row = col = 0; } void Matrix::ReadMatrix() { cout << ”Enter number of rows and colums: ”; cin >> row >> col; if (row > MAX || col > MAX) row = col = 0; else { cout << ”Enter the ” << row << ”x” << col << ” matrix elements\n”; for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) cin >> entry[i][j]; } cout << endl; }

  35. DisplayMatrix & AddSubtract void Matrix::DisplayMatrix() const { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) cout << setw(8) << fixed << setprecision(2) << entry[i][j]; cout << endl; } cout << endl << endl; } Error_code Matrix::AddSubtract(char c, const Matrix &A, const Matrix &B) { if (A.row != B.row || A.col != B.col) return fail; row = A.row; col = A.col; for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) switch (c) { case ’+’ : entry[i][j] = A.entry[i][j] + B.entry[i][j]; break; case ’–’ : entry[i][j] = A.entry[i][j] – B.entry[i][j]; break; default : return fail; } return success; }

  36. Multiply Error_code Matrix::Multiply(const Matrix &A, const Matrix &B) { if (A.col != B.row) return fail; row = A.row; col = B.col; for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) { entry[i][j] = 0.0; for (int k = 0; k < A.col; k++) entry[i][j] += A.entry[i][k] * B.entry[k][j]; } return success; }

  37. The main() void main() { int choice; do{ cout << ”Enter 1 for addition, 2 for subtraction, 3 for multiplication: ”; cin >> choice; }while (choice < 1 || choice > 3); Matrix A, B, Result; A.ReadMatrix(); B.ReadMatrix(); Error_code outcome; switch (choice) { case 1 : outcome = Result.AddSubtract(’+’, A, B); break; case 2 : outcome = Result.AddSubtract(’–’, A, B); break; case 3 : outcome = Result.Multiply(A, B); break; } if (outcome == fail) cout << ”\nMatrices are not compatible\n”; else { cout << ”\nResult:\n\n” << flush; Result.DisplayMatrix(); } }

  38. Andreas Savva Programming Principles II Lecture Notes 6.2 Inheritance

  39. Motor Vehicles Motor Bikes Cars Street Chopper Saloon 4 x 4 4 doors 5 doors 2 doors Inheritance • In a hierarchy of classes, the classes towards the top are known as “base classes” or “super classes”. Those further down are the “derived classes” or “sub-classes”. • Derived classes are specialisations of base classes, sharing their properties but adding their own.

  40. Inheritance in C++ • In object-oriented languages we can use classes that are already declared as base classes and derive specializations from them. classToday{ public: Today(); void setDate(int, int, int); void Tomorrow(); void displayDate() const; protected: int day; int month; int year; private: char day_str[15]; char month_str[15]; }; classCalendar:public Today { public: Calendar(); void AddBirthday(); void DeleteBirthday(); void printTodayBirthday() const; void displayDate() const; private: int birthdaySize[366]; char birthday[366][10][30]; };

  41. Derived Classes class Today class Calendar methods: Today (constructor) setDate Tomorrow displayDate data members: day month year day_str month_str methods: Calendar (constructor) setDate Tomorrow AddBirthday DeleteBirthday printTodayBirthday displayDate data members: day month year birthdaySize birthday Base class Derived class

  42. Public Inheritance classToday{ public: Today(int, int, int); void setDate(int, int, int); void Tomorrow(); voiddisplayDate()const; protected: int day; int month; int year; private: char day_str[15]; char month_str[15]; }; classCalendar:public Today { public: Calendar(int, int, int); void AddBirthday(); void DeleteBirthday(); void printTodayBirthday() const; voiddisplayDate()const; private: int birthdaySize[366]; char birthday[366][10][30]; }; class Calendar

  43. Protected Inheritance classToday{ public: Today(int, int, int); void setDate(int, int, int); void Tomorrow(); voiddisplayDate()const; protected: int day; int month; int year; private: char day_str[15]; char month_str[15]; }; classCalendar:protected Today { public: Calendar(int, int, int); void AddBirthday(); void DeleteBirthday(); void printTodayBirthday() const; voiddisplayDate()const; private: int birthdaySize[366]; char birthday[366][10][30]; }; class Calendar

  44. Private Inheritance classToday{ public: Today(int, int, int); void setDate(int, int, int); void Tomorrow(); voiddisplayDate()const; protected: int day; int month; int year; private: char day_str[15]; char month_str[15]; }; classCalendar:private Today { public: Calendar(int, int, int); void AddBirthday(); void DeleteBirthday(); void printTodayBirthday() const; voiddisplayDate()const; private: int birthdaySize[366]; char birthday[366][10][30]; }; class Calendar

  45. Calling the base class constructorfrom the derived class • The constructor Today (with parameter values from the parameters of Calendar) is invoked by placing it in a member initialization list. Calendar::Calendar(int d, int m, int y) : Today(d, m, y) { for (int i=0; i<366; i++) birthdaySize[i] = 0; } • If there has been a base class that requires no parameters, then the compiler would ensure that it would be called automatically, before the derived class constructor. • However, even if no parameters are required, it does not harm to invoke the base class constructor explicitly, as above.

  46. 16 12 36 Base class enum hourType {unknown, format12, format24}; class Time { public: Time(int, int, int); void DisplayTime() const; protected: int hour, min, sec; hourType hour_type; }; Time::Time(int h, int m, int s) : hour(h), min(m), sec(s) { hour_type = unknown; } void Time::DisplayTime() const { cout << hour << ’\n’ << min << ’\n’ << sec << endl; }

  47. 4:12:36 pm 16:12:36 Derived classes class Time24:public Time { public: Time24(int, int, int); void DisplayTime() const; }; Time24::Time24(int h, int m, int s) : Time(h, m, s) { hour_type = format24; } void Time24::DisplayTime() const { cout << hour << ’:’ << min << ’:’ << sec << endl; } class Time12:public Time { public: Time12(int, int, int); void DisplayTime() const; }; Time12::Time12(int h, int m, int s) : Time(h, m, s) { hour_type = format12; } void Time12::DisplayTime() const { int h = (hour % 12 == 0 ? 12 : hour % 12); cout << h << ’:’ << min << ’:’ << sec; cout << (hour < 12 ? ” am” : ” pm”) << endl; }

  48. 15:29:30 10:30:45 pm Objects of Derived classes int main() { Time24 t1(15, 29, 30); Time12 t2(22, 30, 45); t1.DisplayTime(); t2.DisplayTime(); return 0; }

  49. 15 29 30 22 30 45 Arrays of Mixed Object Types • The problem with arrays is that each of its members must be of the same type. • However, we can declare an array of pointers to the base class and assign objects of deferent derived classes to it. int main() { Time* t[2]; t[0] = new Time24(15, 29, 30); t[1] = new Time12(22, 30, 45); t[0]->DisplayTime(); t[1]->DisplayTime(); return 0; } • It must be noted however that the function DisplayTime executed is the one belonging to the base class.

  50. Polymorphism • Polymorphism means having many shapes and it refers to the ability to use the same name to perform different functions in different classes. • One form of polymorphism is overloading functions. • Another one is by using virtual functions in the base classes. class Time { public: Time(int, int, int); virtual void DisplayTime() const; protected: int hour, min, sec; hourType hour_type; }; Time::Time(int h, int m, int s) : hour(h), min(m), sec(s) { hour_type = unknown; } void Time::DisplayTime() const { cout << hour << ’\n’ << min << ’\n’ << sec << endl; }

More Related