1 / 57

C++: An Object-Oriented Approach Basic Class Development- CMP109 w 2007

C++: An Object-Oriented Approach Basic Class Development- CMP109 w 2007. ADTs Structures and Classes Visibility - public and private Class scope this pointer static and const member functions Containers and items access. today. HW – any comments , problems, interesting result

trygg
Download Presentation

C++: An Object-Oriented Approach Basic Class Development- CMP109 w 2007

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. C++: An Object-Oriented ApproachBasic Class Development- CMP109 w 2007 • ADTs • Structures and Classes • Visibility - public and private • Class scope • this pointer • static and const member functions • Containers and items access

  2. today • HW – any comments , problems, interesting result • New HW2 – talk briefly about that • Reading chapter 4 and chapter 5

  3. Window Polynomial Stack ADTs 2x3+x2+4x+27

  4. student poker hand stack ADTs in the Base Language • User-defined data types • struct implements ADTs in C • OOP design involves thinking up ADTs • Model key features of problem • Reusable in other code

  5. The Aggregate Type struct • Aggregate components into single variable • Members individually named • Members of various types • Aggregates describe complicated data

  6. Stack of Trays • Add to or take from top of a stack of trays

  7. A Standard ADT Example: stack • Insert and delete data only at top of stack • Last-in-first-out discipline (LIFO) • Pile pops up or pushes down on removal or add • Typical operations push, pop, top, empty, full • C++ implementation can use fixed length char array

  8. Stack Operations • push operator places value on • pop operator retrieves & deletes value • top operator returns top value • empty operator tests if stack is empty • full operator tests if stack is full • Functions with argument list • Pointer to stack parameter allows stack to be modified and avoids call-by-value copying

  9. push top 3 pop empty -1 Stack with ABCD Pushed On max_len 1000 full 999 c c c D C B A

  10. Stack in the Kernel Language (1 of 3) • const int max_len = 1000; • enum { EMPTY = -1, FULL = max_len - 1 }; • struct ch_stack { • char s[max_len]; • int top; • };

  11. Stack in the Kernel Language (2 of 3) • void reset(ch_stack* stk) • { • stk -> top = EMPTY; • } • void push(char c, ch_stack* stk) • { • stk -> s[++stk -> top] = c; • } • char pop(ch_stack* stk) • { • return (stk -> s[stk -> top--]); • }

  12. Stack in the Kernel Language (3 of 3) • bool empty(const ch_stack* stk) • { • return (stk —> top == EMPTY); • } • bool full(const ch_stack* stk) • { • return (stk —> top == FULL); • } • char top(ch_stack* stk) • { • return (stk -> s[stk -> top]); • }

  13. Classes and Abstract Data Types • Class is implementation of abstract data type • Extension of struct in traditional C • Implement user-defined type: functions, operators • Class members may be functions • Public members available to any function • Private members available to member functions • Restricted access (data hiding) is OOP feature • Maintenance, reliability, reuse and modularity

  14. Access foo private data public data private manipulation public operations and functions protected derived objects foo could be stack, complex, string, window

  15. ADT Approach to complex • Interface models abstraction • No commitment to representation • Seamless like native types • Mixed in expressions, I/O, conversions • More reusable • Written independent of a problem choice • Downside • Generally less efficientDesign & implementation more comprehensive

  16. Member Functions: Categories • Constructors/Destructors public • Initialization, conversion, store • Access Functions public • I/O and controlled manipulation of values • Auxiliary Functions private & public • Not directly needed by client but useful by other member functions • Operator & Capability Functions public • Operations performed on class

  17. Access and Keywords Keywords Defaults • structpublic • class private Keywords Availability • public everyone • private class members and friends • protected derived classes Keyword Use • private hidden implementation • public client interface

  18. Heuristic for Access • Data members should be private (or protected) • Access should beprovided through inline member functions

  19. Example: Stack in C++ (1 of 2) • struct ch_stack { • public: //operations as member functions • void reset() { top = EMPTY; } • void push(char c) { top++; s[top] = c;} • char pop() { return s[top--]; } • char top_of() { return s[top]; } • bool empty() { return (top == EMPTY);} • bool full() { return (top == FULL); } • private: //data representation • char s[max_len]; • int top; • enum { EMPTY = -1, FULL = max_len - 1}; • };

  20. My name is Don Knuth! !htunK noD si eman yM Example: Stack in C++ (2 of 2) • main() • { • ch_stack s; • char str[40]={"My name is Don Knuth!"}; • int i = 0; • cout << str << endl; • s.reset(); //s.top = EMPTY illegal • while (str[i]) • if (!s.full()) • s.push(str[i++]); • while (!s.empty()) cout << s.pop(); • }

  21. Comments on the stack Program • Access to hidden variable top controlled • Changed by member function reset • Cannot be accessed directly • Variable s passed to each member function using structure member operator form • Private part contains data description • Public part contains member functions

  22. Scope Resolution Operator :: • C++ inherits notions of block and scope from C • Same identifier used for different objects • Inner block hides outer block • ::variable name accesses external • Scope resolution operator is highest precedence

  23. Example: Scope Resolution Operator • int i = 1; // external i • int main() • { • int i = 2; //redeclares i locally • { • cout << "enter inner block\n"; • int n = i; • int i = 3; • cout << i << " i <> ::i " << ::i • << "\nn = " << n << endl; • } • cout << "enter outer block\n"; • cout << i << " i <> ::i " << ::i << endl; • }

  24. New Class Scope • Classes provide an encapsulation technique • All names declared within a class treated as within their own name space • Distinct from external names, function names, or other class names • Need scope resolution operator

  25. Two Forms of Scope Resolution • Highest precedence operator • Use Form Refers to • ::i unary external scope • foo_bar::i binary class scope • Provides path to identifier • No path is by default external

  26. Unary Form of Scope Resolution • Uncover or access name at external scope hidden by local or class scope • int count = 0; //external variable • void how_many(double w[], double x, int& count) • { • for (int i = 0; i < N; ++i) • count += (w[i] == x); • ++ ::count; //keep track of calls • }

  27. Binary Form of Scope Resolution • Disambiguate names reused within classes • Vital to use with inheritance • class widgets { public: void f(); }; • class gizmos { public: void f(); }; • void f() {.} //ordinary external f • void widgets::f() {.} //f scoped to widgets • void gizmos::f() {.} //f scoped to gizmos

  28. Self Referencing • “C3PO, please bring allthe robots, except those robots that can bring themselves.” Now What?

  29. The this pointer • Implicitly declared self-referential pointer • this only used in a non-static member function • Self-referentiality does not change fact that this is pointer • this—>member_namepoints at member object • *this is actual total object • Can be lvalue or rvalue • this is address of the object pointed at

  30. Example: The this pointer (1 of 2) • class c_pair { • public: • c_pair init(char b) {c2 = 1 + (c1 = b);} • c_pair increment() {c1++; c2++; return (*this);} • c_pair* where_am_I() { return this; } • void print() { cout << c1 << c2 << '\t'; } • private: • char c1, c2; • };

  31. Example: The this pointer (2 of 2) • int main() • { • c_pair a, b; • a.init('A'); • a.print(); • cout << " is at " << a.where_am_I() << endl; • b.init('B'); • b.print(); • cout << " is at " << b.where_am_I() << endl; • b.increment().print(); • return 0; • }

  32. Comments on the this Program • Implicitly provided pointer this used to return incremented value of c1 and c2 • where_am_I returns address of given object • As if c_pair implicitly declared private member c_pair* const this • Poor practice to modify this by casting • Early C++ allowed memory management for objects controlled by assignment to this

  33. static and const Member Functions • Ordinary member functions have explicit and implicit argument lists • Members of the class • static member function cannot modify any members using this • Can be declared independent of any particular declarations of objects of the class type • const member function cannot modify its implicit arguments

  34. Example: static and const (1 of 2) • class salary { • public: • init(int b) { b_sal = b; } • void calc_bonus(double perc) • { your_bonus = b_sal * perc; } • static void reset_all(int p) { all_bonus = p; } • int comp_tot() const { return (b_sal + your_bonus + all_bonus); } • private: • int b_sal; • int your_bonus; • static int all_bonus; //declaration • };

  35. Example: static and const (2 of 2) • int salary::all_bonus = 100; //declaration//and definition • int main() • { • salary w1, w2; • w1.init(1000); w2.init(2000); • w1.calc_bonus(0.2); • w2.calc_bonus(0.15); • salary::reset_all(400); • cout << " w1 " << w1.comp_tot() << " w2 " << w2.comp_tot() << endl; • return 0; • }

  36. Comments on the salary Program • static member all_bonus requires file scope definition • Exists independently of specific salary variables • const comes between end of argument list and front of the code body • Self-referential pointer passed asconst salary* const this • Use :: to invoke static member function

  37. Object Creation • Object requires memory and initial value • Kernel language provides this through declarations that are definitions • void foo(){ int n = 5; double z[10] = { 0.0}; struct gizmo { int i, j; } w = { 3, 4}; . . .}

  38. Comments on the foo() Function (1 of 2) • Objects created at block entry when foo() is invoked • gizmo object w requires eight bytes to represent its two integer members • Array of double object z requires ten times sizeof(double) to store its elements • At exit from foo() deallocation occurs

  39. Comments on the foo() Function (2 of 2) • Typical implementation uses a run-time system stack • int object n on a system with four-byte integers gets this allocated off stack and initialized to 5 • System provides for construction and initialization of objects

  40. Design • Elements of design • Relationships: similar to UML class diagrams or CRC cards • Responsibilities: behavior • Collaborations: other classes that cooperate

  41. Man-Page for Design Patterns (2 of 3) Applicability Recognizing where to apply Structure UML notation for pattern or CRC Participants Classes or objects and responsibilities Collaborations Participants work together

  42. UML - Unified Modeling Language • Graphical depiction of class relationships that helps coder design, document, and maintain object-oriented code • Simple diagram is rectangle that represents class • Depict class • Name, placed at top • Data members, placed in middle • Methods, placed at bottom

  43. UML person nameagebirthday bday() UML Diagram for Class person

  44. Handle Class in UML ch_stk_rep ch_stack tops[ ]push() Pop() ptr push()pop()

  45. Class Diagram • Describes types and relationships • Useful documentation • Some Systems provide automated tools to develop UML with coding • Rational Rose • Relationship depicted by UML includes part-whole, or aggregation, relationship (HASA)

  46. The ch_stack Program (1 of 4) • class ch_stack {public:   void  reset() { ptr -> reset(); }   void  push(char c)      { ptr->push(c); }   char  pop() { return ptr->pop(); }   char  top_of() const { return ptr->top_of(); }

  47. The ch_stack Program (2 of 4) •   bool  empty() const      { return ptr -> empty(); }   bool  full() const      { return ptr -> full(); }private:   ch_stk_rep* ptr;      // opaque pointer};

  48. The ch_stack Program (3 of 4) • class ch_stk_rep {public:   void  reset() { top = EMPTY; }   void  push(char c)      { s[top++] = c; }   char  pop() { return s[top--]; }   char  top_of() const { return s[top]; }

  49. The ch_stack Program (4 of 4) •   bool  empty() const      { return (top == EMPTY); }   bool  full() const      { return (top == FULL); }private:   enum { max_len = 100, EMPTY = -1,           FULL = max_len - 1 };   int   top;   char  s[max_len];};

  50. Handle • Handle type such as ch_stack has representation class class ch_stk_rep pointer • Representation class used to concretely implement handle class • Bridge or handle design pattern

More Related