40
Structured Programming Instructor: Prof. K. T. Tsang Lecture 13:Object 物物 Oriented 物物 Programming (OOP)

Structured Programming Instructor: Prof. K. T. Tsang

  • Upload
    clare

  • View
    16

  • Download
    0

Embed Size (px)

DESCRIPTION

Structured Programming Instructor: Prof. K. T. Tsang. Lecture 13:Object 物件 Oriented 面向 Programming (OOP). What is an Object [ 物件 , 对象 ] ?. In plain English, “ object ” is a “ thing ”. - PowerPoint PPT Presentation

Citation preview

Page 1: Structured Programming Instructor: Prof. K. T. Tsang

Structured Programming Instructor: Prof. K. T. Tsang

Lecture 13:Object 物件Oriented 面向 Programming

(OOP)

Page 2: Structured Programming Instructor: Prof. K. T. Tsang

What is an Object [物件 ,对象 ]?

• In plain English, “object” is a “thing”.• In programming, “object” is the “thing”

(data + functions) that models the real world object that we have to deal with.

• It is easier to group all related data to form a data “object” in the process of problem solving.

Page 3: Structured Programming Instructor: Prof. K. T. Tsang

Classes[ 类 ] and Objects• In our daily life, objects have general properties

(attributes) that characterize the group each object belonged to.

• For example: “I” am a “teacher”.“You” are a “student”.

or “Mr. Fu” is a “teacher”.“Mary” is a “student”.

Both “I”, “You”, “Mr. Fu” & “Mary” are “objects”.“I” & “Mr. Fu” belong to the class of “teacher”.“You” & “Mary” belong to the class of “student”.

Page 4: Structured Programming Instructor: Prof. K. T. Tsang

Object is an instance[ 例 ] of a class

• In programming language, “I” & “Mr. Fu” are instances of the “teacher” class. “You” & “Mary” are instances of the “student” class.

In general, any object in programming is an instance of a class.

The relationship between object and class is like that between variable and type.

Page 5: Structured Programming Instructor: Prof. K. T. Tsang

“class” is a more general form of “struct”

• “struct” in C/C++ is a data structure contains data only.

• “class” in C++ is a structure contains both data and functions (methods) to process the data within the class.

Page 6: Structured Programming Instructor: Prof. K. T. Tsang

Procedural programming vs. Object Oriented Programming

• In C, programming efforts focus on developing “functions”, the procedures to handle data.

• In C++, programming efforts focus on developing “classes”.

• For this reason, C++ is an Object Oriented Programming language.

• C is a procedural programming language.

Page 7: Structured Programming Instructor: Prof. K. T. Tsang

Example of a classclass student {

private :int ID;char name[99];char major[99];char *course_taking[ ];

public :void print_info();void changeMajor (char *ma);void enroll_class(char *class_name);

}

Page 8: Structured Programming Instructor: Prof. K. T. Tsang

Another example of class#define PI 3.14159class circle {

private:double x, y;//coordinates of the centerdouble r; //the radiuspublic:double circumference(){ return 2*PI*r; }double area() { return PI*r*r; }

}

Page 9: Structured Programming Instructor: Prof. K. T. Tsang

C++ File-processing classes#include <iostream>#include <fstream>using namespace std;void main(){ifstream fin;int A[4], r;fin.open("file1.dat"); //open data filefor(r=0; r<4; r++)fin >> A[r]; //read from file into arrayfin.close();

ofstream fout;fout.open("file2.dat"); //open output filefor(r=3; r>=0; r--) //write to filefout << A[r] << ' ';fout.close();

}

Name of a class

Name of an object

Page 10: Structured Programming Instructor: Prof. K. T. Tsang

Data & their operations

• In C, the relationship between data and their associated operations is not clear.

• Operations like % can operate on “int” but not “float”+, -, * or / on “int”, “float” & “double” but not on “char”

Programmer has to be careful in using operations on data.

Functions and data are not related.

Page 11: Structured Programming Instructor: Prof. K. T. Tsang

Operators are functions

• “=” as a function with prototype:int operator= (int a);float operator= (float f);

• “+” as a function with prototype:int operator+ (int a, int b);float operator+ (float a, float b);double +(double a, double b);

c operator= (operator+ (a, b)); //c = a + b;

Page 12: Structured Programming Instructor: Prof. K. T. Tsang

From “struct” to “class”

• A C/C++ struct is a collection of data.• In C++ data and the functions (methods)

operated on them are grouped together in a structure called class.

• A C++ class holds not only data, but also the functions that manipulate the data.

• C++ class also provides protection against improper access of its data.

Page 13: Structured Programming Instructor: Prof. K. T. Tsang

Stack: a C structure to hold dataStack is an algorithm for storing data. Data is

stored in last-in-first-out (LIFO) order#define STACK_SIZE 100//definition of a “stack”stuct stack {int count;int data[ STACK_SIZE ];

}

Functions to manipulate this stack is defined separately.

Page 14: Structured Programming Instructor: Prof. K. T. Tsang

Stack functionsvoid stack_init (struct stack &astack){ //initialize stack

astack.count = 0; //set count=0}void stack_push(struct stack &astack, int idat){ //add data in stack

astack.data[astack.count] = idat;astack.count++; //increase count

}int stack_pop(struct stack &astack){ //take data out

astack.count--; //decrease countreturn astack.data[astack.count];

}

Page 15: Structured Programming Instructor: Prof. K. T. Tsang

Use the stack

main () {struct stack mystack;stack_init(mystack);stack_push (mystack, 11);stack_push (mystack, 21);stack_push (mystack, 8);cout << stack_pop(mystack) << endl;cout << stack_pop(mystack) << endl;cout << stack_pop(mystack) << endl;

}

Result:82111

Page 16: Structured Programming Instructor: Prof. K. T. Tsang

An improved stackclass stack {

private: //data are protected from outside use

int count;int data[STACK_SIZE];

public: //no restriction in using methods

void init(); //initialize the stackvoid push(int idata); //push data inint pop( ); //get data out

}

Page 17: Structured Programming Instructor: Prof. K. T. Tsang

Implement class methods

void stack::init( ) {count = 0;

}void stack::push ( int item ) {

data[count] = item;count++;

}int stack::pop( ) {

count--;return data[count];

}

Outside the class definition, aclass method Is known by itsname preceded by the classname and “::” (double colon).

Page 18: Structured Programming Instructor: Prof. K. T. Tsang

Using the stack classmain( ) {

stack mystack;mystack.init( );mystack.push (11);mystack.push (16);mystack.push (22);mystack.push (9);cout << mystack.pop () << endl;cout << mystack.pop () << endl;cout << mystack.pop () << endl;cout << mystack.pop () << endl;

}

Result:9221611

Page 19: Structured Programming Instructor: Prof. K. T. Tsang

Keyword: privateData in a class are also called attributes.

They are usually protected from outside use by the keyword “private”.

We cannot access any attribute labeled private.

Private attributes can only be used in the implementation of class methods.

int n = mystack.data; //error mystack.data = n; //error

Page 20: Structured Programming Instructor: Prof. K. T. Tsang

Keyword: public• Functions in a class are called methods.

They are usually labeled by the keyword “public”. That means they can be used without restriction.

mystack.init( );mystack.push (11);cout << mystack.pop () << endl;

Page 21: Structured Programming Instructor: Prof. K. T. Tsang

Constructors of object

• C++ allows you to define a class method to create an object of that class with all attributes initialized. This is called the “constructor” and has the same name as the class.

For example, the constructor for the “stack” class is named “stack”.

Outside the class body it is known as “stack ::stack”.

Page 22: Structured Programming Instructor: Prof. K. T. Tsang

A “stack” class with constructor

class stack {private: //data are protected from outside use

int count;int data[STACK_SIZE];

public: //no restriction in using methods

stack(void); //constructorvoid init(); //initialize the stackvoid push(int idata); //push data inint pop( ); //get data out

}

Page 23: Structured Programming Instructor: Prof. K. T. Tsang

A simple constructorstack::stack (void) {

count = 0;}

Constructor can never return anything, so even “void” is not needed as return type.

Constructor is called automatically when an object is first declare.

Page 24: Structured Programming Instructor: Prof. K. T. Tsang

How is constructor used?

//Instead ofmain ( ) {

stack mystack;mystack.init();… //use mystack

} //we can just write:main ( ) {

stack mystack; //constructor called automatically

//no need to initialize as this is done by the constructor

… //use mystack}

Page 25: Structured Programming Instructor: Prof. K. T. Tsang

Parameterized constructor

• Constructor may take parameters as arguments to initialize the newly created object.

Page 26: Structured Programming Instructor: Prof. K. T. Tsang

Example: class friend {

private:char name[50];char phone[50];

public:friend (char aname[ ], char

phonen[ ]);… //rest of the class definition

}

Page 27: Structured Programming Instructor: Prof. K. T. Tsang

friend::friend (char nm[ ], char ph[ ]){

strcpy (name, nm);strcpy (phone, ph);

}

Page 28: Structured Programming Instructor: Prof. K. T. Tsang

Overloaded constructorclass friend {

private:char name[50];char phone[50];

public:friend (void);friend (char aname[ ]);friend (char aname[ ], char phonen[ ]);… //rest of the class definition

}

Page 29: Structured Programming Instructor: Prof. K. T. Tsang

friend::friend (void){

strcpy (name, “none”);strcpy (phone, “none”);

}friend::friend (char nm[ ]){

strcpy (name, nm);strcpy (phone, “none”);

}friend::friend (char nm[ ], char ph[ ]){

strcpy (name, nm);strcpy (phone, ph);

}

Page 30: Structured Programming Instructor: Prof. K. T. Tsang

main ( ) {friend friend1;//constructor without argument called

friend friend2(“Li John”);//constructor with 1 argument called

friend friend3 (“Li John”, “13922223333”);//constructor with 2 arguments called

}

Page 31: Structured Programming Instructor: Prof. K. T. Tsang

Attention:

If you have not defined a constructor that takes no argument, you cannot declare an object without specifying an argument.

//if friend (void) is not definedfriend my_good_friend; //error

Page 32: Structured Programming Instructor: Prof. K. T. Tsang

Overloaded functions

In C++ we can define function with the same name but with different arguments. They are regarded as different functions by the compiler.

When an overloaded function is called, the compiler will check how many arguments there are and choose the right one to use.

Page 33: Structured Programming Instructor: Prof. K. T. Tsang

Copy constructorCopy constructor is a constructor used to

make an exact copy of an object (of the same class).

friend::friend (friend o_friend){

strcpy (name, o_friend.name);strcpy (phone, o_friend.phone);

}

Page 34: Structured Programming Instructor: Prof. K. T. Tsang

main ( ) {friend friend1friend friend2(“Li John”);friend friend3 (“Li John”, “13922223333”);//create a copy of friend3

friend friend4 (friend3);//copy constructor called

…}

Page 35: Structured Programming Instructor: Prof. K. T. Tsang

Destructor

Constructor is automatically called when an object is created. Likewise, destructor is called automatically when the object goes out of scope or when a pointer to the object is deleted.

The name for a destructor is the class name with a ‘~’ in front of it,

e.g. ~stack(void)

Page 36: Structured Programming Instructor: Prof. K. T. Tsang

Every class should have a constructor and a destructor. If you do not write these member functions, C++ will automatically generate them.

Page 37: Structured Programming Instructor: Prof. K. T. Tsang

Automatic generated member functions by C++

Default constructor class::class( )

Copy constructor class::class(const class &obj)

Default destructor class::~class( )

Default assignment operatorclass class::operator= (const class &obj )

Page 38: Structured Programming Instructor: Prof. K. T. Tsang

How constructor & destructor are called without you knowing it?

void use_stack (stack local_stack) {local_stack.push(9);local_stack.push(11);

…//more operations on local_stack}main {

stack stack1;stack1.push(2);stack1.push(9);

use_stack (stack1);

cout << stack1.pop( ) << endl;}

Default Constructor called

Copy constructor called:

local_stack.stack(stack1);

Default destructor called after

local_stack out of scope:

local_stack.~stack();

Page 39: Structured Programming Instructor: Prof. K. T. Tsang

Summary

• “class” is a data structure similar to “struct” in C.

• “object” is an instance of a “class”.• “class” contains data (attributes) and

member functions (methods).• All classes have at least a constructor

and a destructor for object creation and deletion.

Page 40: Structured Programming Instructor: Prof. K. T. Tsang