Upload
phoebe-mccoy
View
221
Download
3
Embed Size (px)
Citation preview
Chapter 15 C++ Function
By C. Shing
ITEC Dept
Radford University
Slide 2
Objectives Understand how to create and free dynamic
memory Understand the scope rule Understand pass by reference Understand member functions Know how to write inline functions Understand function overloading Understand static function Understand template function and virtual function
Slide 3
Dynamic Memory Create a memory pointed by memPtr (calls constructor)Form: type * memPtr=new type;Example: int * numberPtr=new int;
Destroy the dynamic memory memPtr(calls destructor)Form: delete memPtr;Example: delete memPtr;
Slide 4
Dynamic Memory (Cont.) Create an array of memory
pointed by arrayPtrForm: type * arrayPtr=new type[SIZE];Example: int * numberarrayPtr=new int[SIZE];
Destroy the dynamic array memory arrayPtrForm: delete [] arrayPtr;Example: delete [] numberarrayPtr;
Slide 5
Scope Rule The variable is meaningful and unique
in its defined block The local variable redefined scope precedes
the global variable if use the same name.
The global variable can be referred using
::local variable name
Slide 6
Scope Rule (Cont.)Example:int number = 10;Int main(){
int number = 100; cout << “ local number= “<<number; cout << “ global number= “<<::number;}
Slide 7
Pass By Reference The function directly access the variables
passed
in using reference.
(This is different from passing pointers)
Slide 8
Pass By Reference (Cont.)Example:Int main(){
int number=10; byRef(number);
cout << number; // print 100}void byRef(int &number){
number=100;}
Slide 9
Pass By Reference - Example Array of Pointers: Store array of stringsAssume that array w has 5 cells, each stores an address of strings as follows:w[0]=100=address of string “this”w[1]=200=address of string “is”w[2]=300=address of string “a”w[3]=400=address of string “snow”w[4]=500=address of string “day”
Slide 10
Pass By Reference – Example (Cont.)
Bubble sort for array w: To call sort_strings – sort_strings(w, size) To use bubble sort to sort the array w:void sort_strings (char * w[], int n){ int i, j; for (i=0; i<n; ++i) for (j=i+1; j<n;++j)
if (strcmp(w[i],w[j])>0) swap (w[i], w[j]);
}
Slide 11
Pass By Reference – Example (Cont.) Example: (Cont.) You may also write it asvoid swap (char * &s, char * &t){ char *tmp; tmp=s; s=t; t=tmp;}
Slide 12
Pass By Reference – Example (Cont.)
Without using class:
bubble.cpp
bubble_data.txt
Using class:
bubbleclass.cpp
bubble_data.txt
Slide 13
Pass By Pointer – Example (Cont.)Bubble sort for array w: To use bubble sort to sort the array w:void sort_strings (char *w[], int n){ int i, j; for (i=0; i<n; ++i) for (j=i+1; j<n;++j)
if (strcmp(w[i],w[j])>0) swap (&w[i], &w[j]);
}
Slide 14
Pass By Pointer – Example (Cont.) Example: (Cont.) The swap function isvoid swap (char *s[], char *t[]){ char *tmp; tmp=*s; *s=*t; *t=tmp;}
Slide 15
Pass By Pointer – Example (Cont.) Using class:
bubbleclassPtr.cpp
bubble_data.txt
Slide 16
Functions member functions:
only functions that can access member in the class Default constructor: missing parameters will be
initialized automatically by the default values inline function:
short function that can fit in one line constant function: function that does not change any
member data, not allowed for constructor or destructor.
A non-constant function is not allowed to access
constant object.
Slide 17
Functions (Cont.) friend function:
not a member function but can access member
data static function (no this pointer available)
function that returns
static variable (share among all objects created)
without any object exists
Slide 18
Functions (Cont.) Overloading
Function overloading: function with different
argument list, each function performs different
task Operator overloading: rewrite rule for existing
operator on object (not change operator precedence
nor the operator characteristics)
Slide 19
Functions (Cont.) Template
Template function: same task for different
data types Class template: specify template for entire class member data
and member functions
Slide 20
Functions (Cont.) Virtual function: used to specify interface
function and will be implemented in various
inherited classes (discussed in Polymorphism)
Slide 21
Member Function – Default Constructor Form:
Class Name (type = default value, …)
Example:
default constructor for 2D Point class
Point (int=0, int=0);
Slide 22
Member function - inlineExample:Class 3DPoint{
public: 3DPoint(double =0.0, double =0.0,
double =0.0); double getX() { return x;} // this is inline function
…private:
double x, y, z;}
Slide 23
Member function - constantExample:Class 3DPoint{
public: 3DPoint(double =0.0, double =0.0,
double =0.0); double getX() const { return x;} // constant function
…private:
double x, y, z;}
Slide 24
Member function – inline and constant function Example
Using class: a 3D Point class
point.cpp
Use this pointer for cascading member
function call
pointThis.cpp
Slide 25
Member function - friendExample:Class Point{
friend Point &setPoint(double, double, double);public:
Point(double =0.0, double =0.0, double =0.0);
double getX() const { return x;} // constant function…
private:double x, y, z;
}
Slide 26
Member function – friend (Cont.)Example: (Cont.)Point &setPoint(Point &p,
double sx, double sy, double sz){
p.x = sx;p.y = sy;p.z = sz;
return p;}
Slide 27
Member function – friend function Example
Using class: a 3D Point class
pointFriend.cpp
Slide 28
Member function - staticExample:Class Point{
friend Point &setPoint(double, double, double);public:
Point(double =0.0, double =0.0, double =0.0);
…// static function to access static member datastatic int howmany ();
private:double x, y, z;static int pointCount;
}
Slide 29
Member function – static (Cont.)Example: (Cont.) // initialize static member dataint Point::pointCount=0;
// constructorPoint::Point(double sx, double sy, double sz)// member initializer: assign sx to x, sy to y and sz to z:x(sx), y(sy), z(sz)
…pointCount++;
}
Slide 30
Member function – static (Cont.)Example: (Cont.) // static function definitionint Point::howmany(){
return pointCount;}
// main functionint main(){
…cout<< "Total number of points created = "<<Point::howmany()<<endl;
}
Slide 31
Member function – static function Example
Using class: a 3D Point class
pointStatic.cpp
Slide 32
Operator OverloadingExample:
Class Point{
friend istream &operator>> (istream &, Point &);public:
Point(double =0.0, double =0.0, double =0.0);
…private:
double x, y, z;}
Slide 33
Operator Overloading (Cont.)Example: (Cont.) // input form: (m,n,r) istream &operator>> (istream &input, Point &p){
input.ignore();input >> p.x;input.ignore();input >> p.y;input.ignore();input >> p.z;input.ignore(5,'\n');return input;
}
Slide 34
Operator Overloading (Cont.)Example: (Cont.)int main(){
Point p, q;p.output();cout<<"Please enter in 2 points in the form: (m,n,r),” << “ e.g. (1.2,3.45,67.891)";cin >> p >> q;p.output();q.output();cout << '\n';
}
Slide 35
Operator Overloading (Cont.) Example
Using class: a 3D Point class
overload.cpp
Slide 36
Template Function Form:
template <class T1, class T2>
returntype functionname (T1 var1 , T2 var2)
{
…
}
Slide 37
Template Function (Cont.) Example: template function for swap
template <class T>void Bubble::swap(T &x , T &y){
T tmp;
tmp = x;x = y;y = tmp;
}
Slide 38
Template Function (Cont.)
bubbleclass_template.cpp
bubble_data.txt
Slide 39
Class template Form:template <class T>class classname {public:
classname();returntype memberfunction (T var1, …);T memberfunction (T var1, …);~ classname();
private:T var3; int var4, …;;
};
Slide 40
Class template (Cont.) Form: (Cont.)
template <class T>
classname<T>::classname ()
{
…
}
Slide 41
Class template (Cont.) Example: A Bubble sort classtemplate <class T>class Bubble {public:
Bubble();void PrintData();void sort();~Bubble();
private:T student[MAX_CLASS_SIZE]; int numStudents;void swap(T &x , T &y);
};
Slide 42
Class template (Cont.) Example: A Bubble sort class (Cont.)template <class T>Bubble<T>::Bubble(){
numStudents=0;
while (cin>>student[numStudents]) {numStudents++;
}}
Slide 43
Class template (Cont.) Complete Example:
No template:
bubbleclass_string.cpp
bubble_data.txt
Slide 44
Class template (Cont.) Complete Example: (Cont.)
Use class template :
bubble_classtemplate1.cpp
bubbleclasstemplate1_data.txt (string data)
bubble_classtemplate2.cpp
bubbleclasstemplate2_data.txt (int data)
Slide 45
References Deitel & Deitel: C How to Program, 4th ed.,
Chapter 15, 16 & 17, Prentice Hall