c++: an object-oriented approach basic class development- cmp109 w 2007
DESCRIPTION
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 - PowerPoint PPT PresentationTRANSCRIPT
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
ADTs
2x3+x2+4x+27
Polynomial Stack
Window
4
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
student poker hand stack
5
The Aggregate Type struct
Aggregate components into single variable
Members individually named
Members of various typesAggregates 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 listPointer to stack parameter allows stack
to be modified and avoids call-by-value copying
9
Stack with ABCD Pushed On
pop
push
top 3
empty -1
full 999
A
B
C
D
max_len 1000
cc
c
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 typeExtension of struct in traditional C
Implement user-defined type: functions, operators
Class members may be functionsPublic 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 typesMixed in expressions, I/O, conversions
More reusableWritten independent of a problem choice
DownsideGenerally less efficient
Design & implementation more comprehensive
16
Member Functions: Categories
Constructors/Destructors publicInitialization, conversion, store
Access Functions publicI/O and controlled manipulation of values
Auxiliary Functions private & public
Not directly needed by client but useful by other member functions
Operator & Capability Functions publicOperations performed on class
17
Access and Keywords
KeywordsKeywords DefaultsDefaultsstruct public
class private
KeywordsKeywords AvailabilityAvailabilitypublic everyone
private class members and friends
protected derived classes
KeywordKeyword UseUseprivate 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
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();}
My name is Don Knuth!!htunK noD si eman yM
21
Comments on the stack Program
Access to hidden variable top controlledChanged by member function resetCannot 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 externalScope resolution operator is
highest precedence
23
Example: Scope Resolution Operator
int i = 1; // external iint 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 scopefoo_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 fvoid widgets::f() {.} //f scoped to widgetsvoid 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 pointerthis only used in a non-static member function
Self-referentiality does not change fact that this is pointer
this—>member_name points at member object
*this is actual total objectCan 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 definitionint 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 as const 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 topData members, placed in middleMethods, placed at bottom
43
UML
person
nameagebirthday
bday()
UML Diagram for Class person
44
Handle Class in UML
ch_stk_rep
tops[ ]
push()Pop()
ch_stack
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)
ch_stack
ptr
push()
ch_stk_rep
tops[]
push()
Handle Class in UML
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
51
Object Oriented Design Focus
Identification of objects
Hierarchical organization of classes
Implementation and design process merge
Reuse of objects
Control & process is not as often reusable
"There is no widely accepted OOD method"-Winblad, et. al.
52
Using Existing Designs
Mathematical and scientific community standard definitions readily coded as ADTs
Complex numbers Rationals
Matrices Polynomials
Programming community has experience with standard container classes
Stack Associative array
Binary tree Queue
53
Invertibility in Design
Invertibility - inverse member functions
In math, addition and subtraction are inverses
In a text editor, add and delete are inverses
Some commands are their own inverses: negation
54
Success of Invertibility in Nonmath Context
Thank goodness for the UNDO command!
Use the UNDELETEfunction toget it back!
Give me back my file!
55
Completeness of Design
Completeness best seen in Boolean algebra, where nand operation suffices to generate all possible Boolean expressions
Boolean algebra taught with negation, conjunction, disjunction as basic operations
Completeness by itself is not enough
Large set of operators is more expressive
56
Orthogonality in Design
Each element of design should integrate and work with all other elements
Elements of basic design should not overlap or be redundant
System that manipulates shapes functions should be able to position shape anywhere
Horizontal moveVertical moveRotate operation
57
Invest in existing libraries
Avoid deep hierarchies
Avoid whiz-bang featuresOne task: one member function
Avoid non-standard operator overloading
Dr. P’s Prescriptions