Upload
oscar-pierce
View
216
Download
0
Embed Size (px)
Citation preview
1
159.234159.234 LECTURE LECTURE
Review for Finals 2009Review for Finals 2009
xx
OOP
2
6 Questions
Final ExamFinal Exam
Q1. 20 marksQ2. 8 marksQ3. 12 marksQ4. 9 marksQ5. 12 marksQ6. 9 marks
Total = 70 marks
Different questions are worth differentnumber of marks.
87% - C++13% - Java
3
EssentialsEssentials
Dynamic memory handling, pass by address, pass by reference.
String Stream processing, file handling
Application: Class design and analysis
Constructors, Destructors, data members, member functions
Access modifiers, static variables, virtual functions & destructors
Inheritance, Polymorphism, Function Templates, class Templates
STL: vector, list, map; Algorithms: find, sort, erase, insert
Java: Features removed from C++
Function Overloading, Operator Overloading
Java: inheritance, interfaces, parameter passing, garbage collection
4
Memory Allocation, Deallocation in C++Memory Allocation, Deallocation in C++
Dynamic Memory HandlingDynamic Memory Handling
Memory leak.
new and delete operators
• This is important because mishandling pointers could easily cause your program to crash.
11
5
Memory
POINTERS
159.234
A pointer may be on the stack – but what it points to may be on the heap. Failing to free heap memory before exiting a function will leave memory on the heap that no longer has a pointer pointing to it.
This memory can never be recovered – it is called a memory leakmemory leak.
Get into the habit of always freeing memory. Even when the program exits.
• Only C++ Memory will be covered in the exam.
6
C-Memory vs. C++ Memory
New 1-D Array allocation via function call
159.234
int alloc1D(char **p, int elements){ (*p) = (char*) malloc(elements * sizeof(char));
if((*p) == NULL) return 0; else return 1; }
char *p; if(alloc1D(&p, 5)) { strcpy(p, "hello"); cout << "at main(): p = " << p << endl;}
free(p);
int new1D(char *&char *&p, int elements){
p = new charchar[elements];
if(p == NULL) return 0;else return 1;
}
char *pchar *p; if(new1D(p, 5)) { strcpy(p, "hello"); cout << "at main(): p = " << p << endl;}
delete [] p;
7
C-Memory vs. C++ Memory
New 2-D Array allocation via function call
159.234
int alloc2D(char ***p, int rows, int cols){
(*p) = (char **) malloc(rows * cols * sizeof(char *));
if((*p) == NULL) return 0;else return 1;
for(int i=0; i < rows; i++){ //(*p)[i] = (char *) malloc(cols * sizeof(char)); //OK *((*p)+i) = (char *) malloc(cols * sizeof(char)); //OK //(*p)+i) = (char *) malloc(cols * sizeof(char)); //ERROR!
if( *((*p)+i) == NULL) return 0; else return 1; }}
int new2D(char **&char **&p, int rows, int cols){
p = new char*char*[rows]; //array of pointers to char
if(p == NULL) return 0;else return 1;
for(int i=0; i < rows; i++){
p[i] = new charchar[cols]; //array of characters
if( p[i] == NULL) return 0; else return 1;
}}
8
C-Memory vs. C++ Memory
New 2-D Array allocation via function call
159.234
char **s;
if(alloc2D(&s,rows,cols)){ s[0] = "FILE"; s[1] = "EDIT"; s[2] = "QUIT"; for(int i=0; i < rows; i++){ cout << "s[" << i << "]= " << s[i] << endl; }}//------------------------------for(int i=0; i < rows; i++){ free(s[i]);}free(s);
char **s;char **s;
if(new2D(ss,rows,cols)){ strcpy(s[0] , "FILE"); strcpy(s[1] , "EDIT"); strcpy(s[2] , “QUIT"); for(int i=0; i < rows; i++){ cout << "s[" << i << "]= " << s[i] << endl; }}
//------------------------------// free-up memoryfor(int i=0; i < rows; i++){ delete [] s[i];}delete [] s;
9
String Stream ProcessingString Stream Processing22
10
Serves as a conduitconduit to an anonymous string which can be readwith the built-in ossoss.str() .str() function that is bound to the ossoss object
ostringstreamostringstream ossoss; int n = 44; float x = 3.14;
ossoss << "Hello!\t" << n << '\t' << x; string s = ossoss.str();.str();
cout << endl << s << endl;
Output String StreamOutput String Stream
Remember sprintf()?, how does it compare to this one?output_string_stream.cpp
#include <sstream>
11All extractions from ississ will come from the contents of buffer, as ifas ifit were an external fileit were an external file.
const string buffer = oss.str(); istringstreamistringstream ississ(buffer); string word; int m; float y; ississ >> word >> m >> y; s = ississ.str(); cout << endl << s << endl; cout << "word = " << word << endl; cout << "m = " << m << endl; cout << "y = " << y << endl;
Input String StreamInput String Stream
ississ is defined and bound to bufferbuffer
Contents of bufferbuffer can be accessedas elements of a string, or by formatted input through the ississobject.
Remember sscanf()?, how does it compare to this one?
input_string_stream.cpp
12
#include <iostream>#include <fstream>#include <iomanip>#include <string>#include <sstream>using namespace std;int main(){
string s1("mydata.txt"); ifstream inin( s1.c_str() );
char buffer[1024]; while( inin.getline( buffer, 1024 ) ){
string stemp( buffer ); cout << "Line is:" << stemp << endl;
if( stemp[0] != '#' ){ stringstream stris( stemp ); double d1, d2; stris >> d1 >> d2; cout << d1 << "," << d2 << endl; } cout << endl; } inin.close(); return 0;}
Using string example• Input file:1.0 2.01.0 2.01.1 2.41.1 2.41.8 2.81.8 2.8##1.34 2.991.34 2.991.4 8.991.4 8.99
• Example Output:Line is:1.0 2.0Line is:1.0 2.01,21,2
Line is:1.1 2.4Line is:1.1 2.41.1,2.41.1,2.4
Line is:1.8 2.8Line is:1.8 2.81.8,2.81.8,2.8
Line is:#1.34 2.99Line is:#1.34 2.99
Line is:1.4 8.99Line is:1.4 8.991.4,8.991.4,8.99
open a file
Read one line of text, if there’s any available
close file
13
#include <iostream>#include <fstream>#include <iomanip>#include <string>#include <sstream>using namespace std;int main(){
string s1("mydata.txt"); ifstream in( s1.c_str() );
char buffer[1024]; while( in.getline( buffer, 1024 ) ){
string stemp( buffer ); cout << "Line is:" << stemp << endl;
if( stemp[0] != '#' ){ stringstream stris( stemp ); double d1, d2; stris >> d1 >> d2; cout << d1 << "," << d2 << endl; } cout << endl; } in.close(); return 0;}
int main(){ string s1("mydata.txt"); ifstream in( s1.c_str() );
string buffer; while(getline( in, buffer ) ) {
cout << "Line is:" << buffer << endl;
if( buffer[0] != '#' ){ istringstream stris( buffer ); double d1, d2; stris >> d1 >> d2; cout << "data: " << d1 << "," << d2 << endl; } cout << endl; } in.close(); return 0;}
File_stringstream2.cpp
Alternatively: (no C-style char*)
Tank GameTank Game
ApplicationApplication
Designed to allow the students to apply everything they’ve learned about OOP. This also helps the students to realise how important and effective OOP is in simplifying the development of the game.
33
Try to imagine re-writing the codes you have submitted into its corresponding non-OOP form. How much more difficult the codes would turn out?
15
Tank GameTank Game
ApplicationApplication
See Lecture 16-Developing the Tank Game
World-to-Device coordinates representation
Using STL to implement the bombs with shrapnels
The sophistication of Physics were abstracted, encapsulated and injected using classes.
You should be able to describe the concept at least and come up with a class implementation (no need to memorize formulas).
How to implement a vector of bombs?
Interaction between classes: Tank, bomb, etc.
Inheritance, polymorphism, friend classes & functions
33
See spikes*.cpp
16
Transformation Equations
WORLD-to-DEVICE COORDINATES
159.234
1280 x 1024 pixels
100,000,000 miles x 500,000 miles
World System of Coordinates Device System of Coordinates
+x
+y+x
+y0
0
(Xworld,Yworld)(XDevice,YDevice)
17
World-to-Device Coordinates
TRANSFORMATION EQUATIONS
159.234
12
12
XX
XX
worldBoundworldBound
ddeviceBounddeviceBounxSlope
11*tx_intercep XX WorldBoundXslopedDeviceBoun
tx_intercep* XX WorldXslopeDevice
• You don’t need to memorize the equations to prepare for the exam.
18
World-to-Device Coordinates
Data Structures, data members
159.234
outputs: x, y (device coordinates) - int int
Inputs: x, y (World coordinates) - double double BoundaryType WorldBound; BoundaryType DevBound;
double xSlope, xInt; double ySlope, yInt;
Does not change too often, only during initialisation and after zooming-in / zooming-out.
19
World-to-Device Coordinates
Data Structures, data members
159.234
class Transform{...private:
BoundaryType WorldBound;BoundaryType DevBound;
double xSlope, xInt;double ySlope, yInt;
};
typedef struct { double x1,y1,x2,y2;} BoundaryType;
const double g = 9.8;
20
Projectile Motion
PHYSICS EQUATIONS
159.234
where g = 9.8 m/sec.2 pull of gravity
Vo in m/sec. initial velocity
t in sec. time
tVox *cos*
tVogty *sin*2
1 2
Modifying timetime will allow you tocalculate the next xx & yy coordinatesof the object.
21
(Non-OOP) (Non-OOP) Projectile Motion
PUTTING THE PIECES TOGETHER (non-OOP)
159.234
// initGraphics here// initBoundaries here t=0.0; while(t < tf) { cleardevice(); setcolor(RED); circle (xDev(x(t, Vo, Theta)),yDev(y(t, Vo, Theta)), 12); t=t+tinc;
}
x() - implements a Physics Equation for x-coordinate calculation
xDev() - World-to-Device Transformation Function
//circle(x, y, radius)
class TransformTransform{
public:
//constructor
TransformTransform(BoundaryType WBound, BoundaryType DBound) :: WorldBound(WBound), DevBound(DBound) {
//calculate slope and intercept//calculate slope and intercept
if((WorldBound.x2-WorldBound.x1) == 0)
xSlope = (DevBound.x2-DevBound.x1)/(WorldBound.x2- WorldBound.x1+.001);
else
xSlope = (DevBound.x2-DevBound.x1)/(WorldBound.x2-WorldBound.x1);
xInt = DevBound.x1-xSlope*WorldBound.x1;
//....and so on...//....and so on...
}
int xDevxDev(double xWorld) const {return (int)ceil(xSlope*xWorld+xInt); } //from world to device //from world to device
...
private:
BoundaryType WorldBound, DevBound;
//...and so on...//...and so on...
};
22
Slope and intercept values need to be calculated before the transformation from world to device could be performed.
devicedevice
//Instantiation
Transform tfmtfm(WBound, DBound);
//passing the object as an argument to the drawing methods
tank.draw(tfmtfm);
//draw function formal parameter definition
void Tank::draw(const Transform & tt) {
//...implementation here
fillellipse(t.xDev( t.xDev( headX )), t.yDev( t.yDev( headY )) …);
}
23
Only one instance is necessary for all animated objects in the game!
Passed as a reference to a constant
24
TemplatesTemplates
Final ExamFinal Exam
Operator overloading
arguments
Using assert()
You should know the details of implementation (e.g. assignment operator, subscripting operator, etc.)
Formal parameters, actual parameters
Constructors, Destructors
25
Connecting Classes via Connecting Classes via CompositionComposition
Final ExamFinal Exam
Data members and Member Functions
You should know what happens to them when you connectclasses via Composition.
Constructors, Destructors
26
Connecting Classes via Connecting Classes via InheritanceInheritance
Final ExamFinal Exam
See Lectures 15 & 16
Data members and Member Functions
You should know what happens to them when you connectclasses via Inheritance.
Constructors, Destructors
Multiple Inheritance
27
STLSTL
Final ExamFinal Exam
See Lectures 20, 21 & 22
Containers: vector, list, map
Algorithms: find, sort, insert, erase
Iterators
28
JavaJava
Final ExamFinal Exam
Program structure, JVM
Main function, creation & deletion of objects from the heap,how Java supports cross-platform application development?
Inheritance in Java
Paramater passing
how to pass objects?
Requirements when a class extends another class,What happens if you put a class inside another class?
See Java 1,2,3
See Java 2
See Java 3
Interface in Java
What happens when a class implements an interface?
See Java 3
29
C++Static Members of Classes
159.234
Static members of classes:If a member variable is declared static, there is only one instance of that in the program. A static variable is common to all class variables.
class P {public: static char c;static char c;};
char P::c = 'W';char P::c = 'W';int main() { P x,y; cout << x.cx.c; x.c x.c = 'A'; cout << y.cy.c;}
30
1. When a copy of an object is required, such as in call-by-valuecall-by-value. SStr p;tr p; display(p);display(p);
2. When returningreturning an object by value from a function.
Point findMiddlePt ( Point p1,Point p2){Point findMiddlePt ( Point p1,Point p2){ Point temp ;Point temp ; //---do something
return temp;return temp;}}
3. When initializinginitializing an object to be a copy of another object of the same class.
Str x;Str x;//...other statements here
Str y(x);Str y(x); //y declared and initialized with xor
Str y = x;Str y = x; //y declared and initialized with x
When is a copy constructor called?SUMMARY
31
Friend Functions/Classes
Friend functions
A 'friend'friend' function has access to access to all 'private' members all 'private' members of the class for which it is a 'friend'.
To declare a 'friend' function, include its prototypeprototype within the class, preceding it with the C++ keyword 'friend'.
32
Friend Functions/Classes
class TT { public: friend void a();friend void a(); int int mm();(); private: // ...};
void a() {// can access // private data in T...}
class SS { public: friend int friend int TT::m();::m(); //...};
class X {public: friend class friend class TT;; //...};
Global function a()a() can access private data in class TT
m()m() can access private data in class SS
all functions of class TT can access private data in class XX
friendfriendss should be used with caution: they by-pass C++’s data hiding principle.
It is the responsibility of the code for which access is to be given to say who it’s friends are - i.e. who does it trust!
33
Defining Operator OverloadingDefining Operator Overloading
To define an additional task to an operator, we must specify what itmeans in relation to the class to which the operator will be applied.
This is done with the help of a special function called operator function which describes the task.
General form of an operator function:
return typereturn type classname :: operator (op-arglist){ function body //task defined}
Operator being overloaded
operator is the function name
34
PolymorphismPolymorphism
class two_dtwo_d {public: two_d(double a, double b) : x(a), y(b) {} virtualvirtual double areaarea(void) {return 0;return 0;}
protected: double x,y;};
area area is a called a virtualvirtual function.
35
PolymorphismPolymorphism
class rectrect : public two_dtwo_d{public: rect(double a, double b, double ht, double wd) : two_d(a,b), h(ht), w(wd) {} virtualvirtual double areaarea(void) {return w * h;return w * h;}
private: double h,w;};
area area is a called a virtualvirtual function.
36
PolymorphismPolymorphism
area() is a called a virtualvirtual function.
The run-time system knows the types of objects that pointers point to!
The appropriate The appropriate function is called when function is called when we ask forwe ask for p[i]->area()p[i]->area()
for (int i=0;i<4;i++) { total += p[i]->area()p[i]->area();
}
Here’s the code segment again:
circle c,d; rect e,f; two_d* p[4]; p[0]=&c; p[1]=&d; p[2]=&e; p[3]=&f;
37
PurePure Virtual Function Virtual Function
class two_d {public: two_d(double a, double b) : x(a), y(b) {} virtual double area(void) virtual double area(void) = 0= 0;;protected: double x,y;};
38
TemplatesTemplatesExample: VectorExample: Vector
Data members & some extra methods:Data members & some extra methods:
1919
template <class T>Vector<T>::Vector(int n=100) : size(n) { assert(n>0); p = new T[size]; assert(p != NULL);}
Constructor:Constructor:
protected: T* data; unsigned size;
void copy(const Vector<T>&);
39
TemplatesTemplates
operator[ ]operator[ ]
1919
template <class T>T& Vector<T>::operator[](int i) { assert((i>=0) && (i<size)); return p[i];}
40
TemplatesTemplates
operator =operator =
1919
template <class T> Vector<T>& operator=(const Vector<T>& v) { if(size > 0) { cout << "deleting previous contents..." << endl; delete [] data; } size = v.size; data = new T[size];
copy(v); return *this; }
41
TemplatesTemplates
Copy constructorCopy constructor
1919
//Copy constructor: X-X-refVector(const Vector<T>& v) : size(v.size) { cout << "\ncopy constructor called." << endl;
data = new T[size]; copy(v);}
42
TemplatesTemplates 1919
template<class T>void Vector<T> ::copy(const Vector<T>& v) {
// int minSize = (size < v.size)? size : v.size;// for(int i=0; i < minSize; i++) {
for(int i=0; i < size; i++) {data[i] = v.data[i];
}
}
43
TemplatesTemplatesUsing a Template ClassUsing a Template Class
Finally, this is how we use a template class:Finally, this is how we use a template class:
1919
int main() { Vector<int> m(100); m[3] = 34;...}
44
#include <iostream>#include <vector>using namespace std;
int main(){ vector<int> v; vector<int>::iterator it, start, end; for(int i=0;i<10;i++){ v.push_back(i); } cout << "v size = " << v.size() << endl; start = v.begin(); start += 3; // now points at element [3] end = start; end += 4; // now points at element [7] v.erase(start, end ); // erases 3,4,5,6 cout << "v size = " << v.size() << endl; for(it=v.begin();it<v.end();it++){ *it *= 10; } cout << "v contains: "; for(int i=0;i<v.size(); i++){ cout << " " << v[i]; } cout << endl;
}
Output:
% a.out
v size = 10
v size = 6
v contains: 0 10 20 70 80 90
vector<int> v;vector<int> v;A variable-sized vectorA variable-sized vector
the range includes all the elements between start and end, including the element pointed by start but but notnot the one the one pointed by end.pointed by end.
45
map<string,int> m1, m2; map<string,int>::iterator iter; // points to a pair<string,int>
string one("One"); string two("Two"); string three("Three"); string four("Four"); string five("Five");
m1[one] = 1; m2[two] = 2; m1[three] = 3; m2[four] = 4; m1[five] = 5;
for(iter=m1.begin();iter!=m1.end();iter++){ cout << "Found " << iter->second << " keyed by " << iter->first << endl; } cout << endl;
m1.swap(m2);
for(iter=m1.begin();iter!=m1.end();iter++){ cout << "Found " << iter->second << " keyed by " << iter->first << endl; }
Note: map’s iterator is a pointer to a pair - dereferenced using members first and second
Output:
% a.out
Found 5 keyed by FiveFound 1 keyed by OneFound 3 keyed by Three
Found 4 keyed by FourFound 2 keyed by Two
map<key, val>map<key, val>An associative array (or dictionary, or table)An associative array (or dictionary, or table)
• acts like an array whose index can be any type that implements the < operator.• e.g. key=StudentID, val = Student’s data Record
46
struct Entry { string name; int number; friend int operator<(const Entry& e1, const Entry& e2);};
int operator<(const Entry& e1, const Entry& e2) {return (e1.name < e2.name);
}
vector<Entry> v;...sort(v.begin(), v.end());
STL: vectorSTL: vector
47
A map STL contains a built-in find function.
it = phoneBook.findfind("ZNapoleon");
if(it != phoneBook.end()) {cout << "Entry found." << endl;cout << it->first << ", " << it->second << endl;
} else {cout << "Entry is missing." << endl;
}
mapmap<string, int> phoneBook;//...
STL: mapSTL: map