SlideShare a Scribd company logo
Object-Oriented ProgrammingObject-Oriented Programming
(( 物件導向程式設計物件導向程式設計 ))
Lecturer: Liao Ping-Lun (Lecturer: Liao Ping-Lun ( 廖柄㷍廖柄㷍 ))
EMail:EMail: pinglunliao@gmail.compinglunliao@gmail.com
AgendaAgenda
Project Complex classProject Complex class
Project TStack with PersonProject TStack with Person
Inheritance (Inheritance ( 繼承繼承 ))
Polymorphism (Polymorphism ( 多型多型 ))
Overloaded Operators (Overloaded Operators ( 運算子重載運算子重載 ))
operator[] (subscript operator)operator[] (subscript operator)
char city[40] = "Taipei";char city[40] = "Taipei";
cout << city[1] << endl; // display 'a'cout << city[1] << endl; // display 'a'
String opera("The Duck");String opera("The Duck");
char& String::operator[](int)char& String::operator[](int)
{ return str[i]; } // opera[0] = 'T';{ return str[i]; } // opera[0] = 'T';
const char& String::operator[](int i) constconst char& String::operator[](int i) const
{ return str[i]; } // cout << opera[4];{ return str[i]; } // cout << opera[4];
// char ch = opera[3];// char ch = opera[3];
Overloaded Operators (Overloaded Operators ( 運算子重載運算子重載 ))
operator= (assignment operator)operator= (assignment operator)
Person me;Person me;
Person him = me; // not an assignmentPerson him = me; // not an assignment
him = me; // assignmenthim = me; // assignment
為什麼是為什麼是 return by reference?return by reference?
因為修改的是自己因為修改的是自己
Overloaded Operators (Overloaded Operators ( 運算子重載運算子重載 ))
重載重載 MyStackMyStack
operator=operator=
operator[]operator[]
Project Complex ClassProject Complex Class
Default ConstructorDefault Constructor
With default valueWith default value
Copy ConstructorCopy Constructor
Operator overloadingOperator overloading
operator+operator+
operator-operator-
operator*operator*
operator<<operator<<
operator>>operator>>
示範示範
operator+operator+
Project Complex ClassProject Complex Class
SolutionSolution
Pointer and objectPointer and object
String glamour;String glamour;
String *first = &glamour;String *first = &glamour; // assign object address// assign object address
String *gleep = new String;String *gleep = new String; // default constructor// default constructor
// invoke String(const char*) constructor// invoke String(const char*) constructor
String *glop = new String("me me me");String *glop = new String("me me me");
// invoke String(const String&) constructor// invoke String(const String&) constructor
String *favorite = new String(glamour);String *favorite = new String(glamour);
if(glamour < *first)if(glamour < *first) // compare object value// compare object value
Implicit and explicit type conversionImplicit and explicit type conversion
class Stringclass String
{{
//...//...
explicit String( const char* pstr ); // str = String("ABC");explicit String( const char* pstr ); // str = String("ABC");
operator char*();operator char*();
};};
String str;String str;
str = "TEST"; //Error: cannot convert "TEST" to String impstr = "TEST"; //Error: cannot convert "TEST" to String imp
licitlylicitly
char *pstr = str; // char *pstr = (char*)str;char *pstr = str; // char *pstr = (char*)str;
InheritanceInheritance
Is-a relationshipIs-a relationship
Public inheritancePublic inheritance
Initializer list in default constructorInitializer list in default constructor
Virtual member functionVirtual member function
Static binding and dynamic bindingStatic binding and dynamic binding
Abstract base classAbstract base class
Pure virtual functionPure virtual function
Public interfacePublic interface
Is-a & has-a relationshipsIs-a & has-a relationships
直線、矩形是圖形,但畫布上有好多圖形!直線、矩形是圖形,但畫布上有好多圖形!
Inheriting classInheriting class
Base classBase class
Derived classDerived class
Using Derived classUsing Derived class
跟在使用一般類別一樣的語法。跟在使用一般類別一樣的語法。
InheritanceInheritance
Inheritance classInheritance class
class RatedPlayerclass RatedPlayer: public: public TableTennisPlayerTableTennisPlayer
{{
private:private:
int rating;int rating;
public:public:
......
};};
Base and Derived Class ObjectBase and Derived Class Object
Access specify without inheritanceAccess specify without inheritance
Initilizer ListInitilizer List
Derived classDerived class 設定設定 Base classBase class 的的 privateprivate
member variablesmember variables 時時
RatedPlayer::RatedPlayer(unsigned int r, const charRatedPlayer::RatedPlayer(unsigned int r, const char
* fn, const char * ln, bool ht) : TableTennisPlayer* fn, const char * ln, bool ht) : TableTennisPlayer
(fn, ln, ht)(fn, ln, ht)
{{
rating = r;rating = r;
}}
RatedPlayer rplayer1(1140, "Mallory", "Duck", true)RatedPlayer rplayer1(1140, "Mallory", "Duck", true)
;;
Initilizer ListInitilizer List
RatedPlayer::RatedPlayer(unsigned int r, const charRatedPlayer::RatedPlayer(unsigned int r, const char
* fn, const char * ln, bool ht) : TableTennisPlayer* fn, const char * ln, bool ht) : TableTennisPlayer
(fn, ln, ht), rating(r)(fn, ln, ht), rating(r)
{}{}
RatedPlayer rplayer1(1140, "Mallory", "Duck", true)RatedPlayer rplayer1(1140, "Mallory", "Duck", true)
;;
Default constructor in derived classDefault constructor in derived class
Completely constructors in base classCompletely constructors in base class
Using initializer list to build up defaultUsing initializer list to build up default
constructor in derived classconstructor in derived class
Data members in initialization in derived clData members in initialization in derived cl
assass
Access specify with inheritanceAccess specify with inheritance
Special relationship between base and derived classSpecial relationship between base and derived class
Using base class methodUsing base class method
Upward castingUpward casting
Downward casting is not allowedDownward casting is not allowed
Using base class methodUsing base class method
RatedPlayer rplayer1(1140, "Mallory", "Duck", true);RatedPlayer rplayer1(1140, "Mallory", "Duck", true);
rplayer1.Name();rplayer1.Name();// derived object uses base method// derived object uses base method
Upward castingUpward casting
RatedPlayer rplayer1(1140, "Mallory", "Duck", true);RatedPlayer rplayer1(1140, "Mallory", "Duck", true);
TableTennisPlayer &rt = rplayer;TableTennisPlayer &rt = rplayer;
TAbleTennisPlayer *pt = &rplayer;TAbleTennisPlayer *pt = &rplayer;
rt.Name();rt.Name(); // invoke Name() with reference// invoke Name() with reference
pt->Name();pt->Name(); // invoke Name() with pointer// invoke Name() with pointer
Downward casting is not allowedDownward casting is not allowed
TableTennisPlayer player("Tara", "Boomdea", false)TableTennisPlayer player("Tara", "Boomdea", false)
;;
RatedPlayer &rrp = player;RatedPlayer &rrp = player; // not allowed// not allowed
RatedPlayer *prp = &player;RatedPlayer *prp = &player; // not allowed// not allowed
Implicit upward castingImplicit upward casting
void method(void method(const Base_class &bcconst Base_class &bc););
void Show(const TableTennisPlayer &rt)void Show(const TableTennisPlayer &rt)
{{
cout << "Name: ";cout << "Name: ";
rt.Name();rt.Name();
cout << "nTable: ";cout << "nTable: ";
if(rt.HasTable()) cout << "yesn";if(rt.HasTable()) cout << "yesn";
else cout << "non";else cout << "non";
}}
TableTennisPlayer player1("Tara", "Boomdea", false);TableTennisPlayer player1("Tara", "Boomdea", false);
RatedPlayer rplayer1(1140, "Mallory", "Duck", true);RatedPlayer rplayer1(1140, "Mallory", "Duck", true);
Show(player1);Show(player1);
Show(rplayer1);Show(rplayer1);
Implicit copy constructorImplicit copy constructor
RatedPlayer sams(1100, "Sams", "Lups", true);RatedPlayer sams(1100, "Sams", "Lups", true);
// invoke implicit copy constructor and up-casting, TableTenn// invoke implicit copy constructor and up-casting, TableTenn
isPlayer(const TableTennisPlayer&);isPlayer(const TableTennisPlayer&);
TableTennisPlayer fakeSams1(sams);TableTennisPlayer fakeSams1(sams);
TableTennisPlayer fakeSams2 = sams;TableTennisPlayer fakeSams2 = sams;
TableTennisPlayer fakeSams3;TableTennisPlayer fakeSams3;
fakeSams3 = sams;fakeSams3 = sams; // assignment op and up-casting// assignment op and up-casting
Inheritance modelInheritance model
PublicPublic
Is-a relationshipIs-a relationship
Illegal relationshipsIllegal relationships
Is-like-a, has-a, is-implemented-as, uses-aIs-like-a, has-a, is-implemented-as, uses-a
PrivatePrivate
ProtectedProtected
BindingBinding
Static binding (early binding)Static binding (early binding) during compiliduring compili
ngng
Dynamic binding (late binding)Dynamic binding (late binding) during execduring exec
utionution
Type compatibility of pointer and referenceType compatibility of pointer and reference
double x = 3.5;double x = 3.5;
int *pi = &x;int *pi = &x; // mismatch pointer types// mismatch pointer types
long &r = x;long &r = x; // mismatch reference type// mismatch reference type
DerivedClass test;DerivedClass test;
BaseClass *pd = &test; // okBaseClass *pd = &test; // ok
BaseClass &rd = test; // okBaseClass &rd = test; // ok
Upward & downward castingUpward & downward casting
class Singer: public Employeeclass Singer: public Employee
{{
public:public:
void range();void range();
};};
class Employeeclass Employee
{{
private:private:
char name[40];char name[40];
public:public:
void show_name();void show_name();
};};
Employee veep;Employee veep;
Singer trala;Singer trala;
Employee *pe = &trala;Employee *pe = &trala; // upward casting// upward casting
Singer *ps = (Singer*)&veep;Singer *ps = (Singer*)&veep; // downward casting// downward casting
pe->show_name();pe->show_name(); // ok// ok
pe->range();pe->range(); // compile error: range() is not a member of Employee// compile error: range() is not a member of Employee
ps->range();ps->range(); // Run time error// Run time error
Upward & downward castingUpward & downward casting
Why ?Why ?
downward casting: run time error.downward casting: run time error.
upward casting: compile error.upward casting: compile error.
Virtual member function & dynamic bindingVirtual member function & dynamic binding
Virtual function uses dynamic binding, whereas,Virtual function uses dynamic binding, whereas,
non-virtual function employs static bindingnon-virtual function employs static binding
Derived_class dc;Derived_class dc; // derived class// derived class
Base_class *bcp;Base_class *bcp; // base class// base class
bcp = &dc;bcp = &dc; // Base_class pointer to Derived_class object// Base_class pointer to Derived_class object
bcp->Function();bcp->Function(); // which version?// which version?
Virtual member function & dynamic bindingVirtual member function & dynamic binding
ExampleExample
Brass Porky("Porcelot Pigg", 381299, 4000.00);Brass Porky("Porcelot Pigg", 381299, 4000.00);
Brass *bp; // base classBrass *bp; // base class
bp = &Porky;bp = &Porky;
bp->ViewAcct(); // which version?bp->ViewAcct(); // which version?
Virtual or non-virtual?Virtual or non-virtual?
Virtual functionVirtual function
Base class member functionBase class member function isis allowedallowed to be rto be r
edefinededefined in derived classin derived class
Non-virtual functionNon-virtual function
Base class member functionBase class member function isis not allowednot allowed toto
bebe redefined in derived classredefined in derived class
How virtual function work?How virtual function work?
ExampleExample
Instrument4.cppInstrument4.cpp
How virtual function work?How virtual function work?
*Virtual function table (vtbl)*Virtual function table (vtbl)
Single ObjectSingle Object
How virtual function work?How virtual function work?
*Virtual function table (vtbl)*Virtual function table (vtbl)
Multiple ObjectMultiple Object
Price for using virtual functionPrice for using virtual function
Extra vtbl space using for every object creExtra vtbl space using for every object cre
ationation
Compiler will create an array to store virtuaCompiler will create an array to store virtua
l function address in every classl function address in every class
Extra time using in finding the function addExtra time using in finding the function add
ressress
Rules for virtual functionRules for virtual function
Constructor cannot be a virtual functionConstructor cannot be a virtual function
Destructor usually be a virtual functionDestructor usually be a virtual function
Friend function cannot be a virtual functionFriend function cannot be a virtual function
Static function cannot be a virtual functionStatic function cannot be a virtual function
Function signature consistence in a redefinFunction signature consistence in a redefin
ed functioned function
If virtual functions are overloaded in base cIf virtual functions are overloaded in base c
lass, then redefined all the functions in derilass, then redefined all the functions in deri
ved classved class
Accessibility for protectedAccessibility for protected
Member functions in classMember functions in class
PolymorphismPolymorphism
ExampleExample
RoughDrawRoughDraw
PracticePractice
加上加上 RRectRRect 和和 EllipseEllipse 兩個類別。兩個類別。
ReferencesReferences
Thinking in C++ (Free E-Book)Thinking in C++ (Free E-Book)
Beginning C++: The Complete LanguageBeginning C++: The Complete Language
(( 中譯:中譯: C++C++ 教學範本教學範本 ))
物件導向程式設計物件導向程式設計 hh
ttp://vr.me.ncku.edu.tw/courses/index-oop.htmttp://vr.me.ncku.edu.tw/courses/index-oop.htm
良葛格學習筆記良葛格學習筆記 httphttp
://caterpillar.onlyfun.net/Gossip/index.html://caterpillar.onlyfun.net/Gossip/index.html

More Related Content

What's hot

Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!
José Paumard
 
Building native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and Pindah
Nick Plante
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentation
Manav Prasad
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
Ganesh Samarthyam
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
David Atchley
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
Pavlo Baron
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
Arturo Herrero
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
José Paumard
 
AST Transformations
AST TransformationsAST Transformations
AST TransformationsHamletDRC
 
OOP Intro in Ruby for NHRuby Feb 2010
OOP Intro in Ruby for NHRuby Feb 2010OOP Intro in Ruby for NHRuby Feb 2010
OOP Intro in Ruby for NHRuby Feb 2010
bturnbull
 
Clojure made simple - Lightning talk
Clojure made simple - Lightning talkClojure made simple - Lightning talk
Clojure made simple - Lightning talk
John Stevenson
 
Go testdeep
Go testdeepGo testdeep
Go testdeep
Maxime Soulé
 
(map Clojure everyday-tasks)
(map Clojure everyday-tasks)(map Clojure everyday-tasks)
(map Clojure everyday-tasks)
Jacek Laskowski
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
HamletDRC
 
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Sungchul Park
 
Free your lambdas
Free your lambdasFree your lambdas
Free your lambdas
José Paumard
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - StockholmJan Kronquist
 
Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
Dave Aronson
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
José Paumard
 
Clojure Interoperability
Clojure InteroperabilityClojure Interoperability
Clojure Interoperability
rik0
 

What's hot (20)

Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!
 
Building native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and Pindah
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentation
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
 
OOP Intro in Ruby for NHRuby Feb 2010
OOP Intro in Ruby for NHRuby Feb 2010OOP Intro in Ruby for NHRuby Feb 2010
OOP Intro in Ruby for NHRuby Feb 2010
 
Clojure made simple - Lightning talk
Clojure made simple - Lightning talkClojure made simple - Lightning talk
Clojure made simple - Lightning talk
 
Go testdeep
Go testdeepGo testdeep
Go testdeep
 
(map Clojure everyday-tasks)
(map Clojure everyday-tasks)(map Clojure everyday-tasks)
(map Clojure everyday-tasks)
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
 
Free your lambdas
Free your lambdasFree your lambdas
Free your lambdas
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
 
Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
 
Clojure Interoperability
Clojure InteroperabilityClojure Interoperability
Clojure Interoperability
 

Similar to Object-Oriented Programming

Naïveté vs. Experience
Naïveté vs. ExperienceNaïveté vs. Experience
Naïveté vs. Experience
Mike Fogus
 
Phylogenetics in R
Phylogenetics in RPhylogenetics in R
Phylogenetics in R
schamber
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scalaparag978978
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
PingLun Liao
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
Clojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMClojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVM
sunng87
 
Strings in c
Strings in cStrings in c
Strings in c
vampugani
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokusHamletDRC
 
13 Strings and text processing
13 Strings and text processing13 Strings and text processing
13 Strings and text processing
maznabili
 
Using Regular Expressions and Staying Sane
Using Regular Expressions and Staying SaneUsing Regular Expressions and Staying Sane
Using Regular Expressions and Staying Sane
Carl Brown
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to PerlSway Wang
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
Paulo Morgado
 
C q 3
C q 3C q 3
Java Annotations and Pre-processing
Java  Annotations and Pre-processingJava  Annotations and Pre-processing
Java Annotations and Pre-processing
Danilo Pereira De Luca
 
Java常见疑惑和陷阱
Java常见疑惑和陷阱Java常见疑惑和陷阱
Java常见疑惑和陷阱Ady Liu
 
You Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager NeedsYou Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager Needs
Roy Zimmer
 
Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)
Phil Calçado
 

Similar to Object-Oriented Programming (20)

Naïveté vs. Experience
Naïveté vs. ExperienceNaïveté vs. Experience
Naïveté vs. Experience
 
Phylogenetics in R
Phylogenetics in RPhylogenetics in R
Phylogenetics in R
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scala
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Php & my sql
Php & my sqlPhp & my sql
Php & my sql
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Clojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMClojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVM
 
Strings in c
Strings in cStrings in c
Strings in c
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
 
13 Strings and text processing
13 Strings and text processing13 Strings and text processing
13 Strings and text processing
 
Using Regular Expressions and Staying Sane
Using Regular Expressions and Staying SaneUsing Regular Expressions and Staying Sane
Using Regular Expressions and Staying Sane
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
C q 3
C q 3C q 3
C q 3
 
Java Annotations and Pre-processing
Java  Annotations and Pre-processingJava  Annotations and Pre-processing
Java Annotations and Pre-processing
 
Java常见疑惑和陷阱
Java常见疑惑和陷阱Java常见疑惑和陷阱
Java常见疑惑和陷阱
 
You Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager NeedsYou Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager Needs
 
Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)
 

More from PingLun Liao

深入探討 C 語言
深入探討 C 語言深入探討 C 語言
深入探討 C 語言
PingLun Liao
 
Git 程式碼版本控制軟體介紹
Git 程式碼版本控制軟體介紹Git 程式碼版本控制軟體介紹
Git 程式碼版本控制軟體介紹
PingLun Liao
 
給沒有程式設計經驗的人
給沒有程式設計經驗的人給沒有程式設計經驗的人
給沒有程式設計經驗的人
PingLun Liao
 
陣列與指標
陣列與指標陣列與指標
陣列與指標
PingLun Liao
 
Perl For Bioinformatics
Perl For BioinformaticsPerl For Bioinformatics
Perl For Bioinformatics
PingLun Liao
 
C++ STL 概觀
C++ STL 概觀C++ STL 概觀
C++ STL 概觀
PingLun Liao
 
C++ Function
C++ FunctionC++ Function
C++ Function
PingLun Liao
 
C 檔案輸入與輸出
C 檔案輸入與輸出C 檔案輸入與輸出
C 檔案輸入與輸出
PingLun Liao
 
Win32 視窗程式設計基礎
Win32 視窗程式設計基礎Win32 視窗程式設計基礎
Win32 視窗程式設計基礎
PingLun Liao
 
Matlab 在機率與統計的應用
Matlab 在機率與統計的應用Matlab 在機率與統計的應用
Matlab 在機率與統計的應用
PingLun Liao
 
Android 2D 遊戲設計基礎
Android 2D 遊戲設計基礎Android 2D 遊戲設計基礎
Android 2D 遊戲設計基礎
PingLun Liao
 
Android 介面設計
Android 介面設計Android 介面設計
Android 介面設計
PingLun Liao
 
Java 視窗程式設計
Java 視窗程式設計Java 視窗程式設計
Java 視窗程式設計
PingLun Liao
 
Java 網路程式
Java 網路程式Java 網路程式
Java 網路程式
PingLun Liao
 
Android introduction
Android introductionAndroid introduction
Android introduction
PingLun Liao
 
RESTful
RESTfulRESTful
RESTful
PingLun Liao
 
Web service
Web serviceWeb service
Web service
PingLun Liao
 
How toprogram
How toprogramHow toprogram
How toprogram
PingLun Liao
 
Object-Based Programming Part II
Object-Based Programming Part IIObject-Based Programming Part II
Object-Based Programming Part II
PingLun Liao
 
Object-Based Programming Part One
Object-Based Programming Part OneObject-Based Programming Part One
Object-Based Programming Part One
PingLun Liao
 

More from PingLun Liao (20)

深入探討 C 語言
深入探討 C 語言深入探討 C 語言
深入探討 C 語言
 
Git 程式碼版本控制軟體介紹
Git 程式碼版本控制軟體介紹Git 程式碼版本控制軟體介紹
Git 程式碼版本控制軟體介紹
 
給沒有程式設計經驗的人
給沒有程式設計經驗的人給沒有程式設計經驗的人
給沒有程式設計經驗的人
 
陣列與指標
陣列與指標陣列與指標
陣列與指標
 
Perl For Bioinformatics
Perl For BioinformaticsPerl For Bioinformatics
Perl For Bioinformatics
 
C++ STL 概觀
C++ STL 概觀C++ STL 概觀
C++ STL 概觀
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
C 檔案輸入與輸出
C 檔案輸入與輸出C 檔案輸入與輸出
C 檔案輸入與輸出
 
Win32 視窗程式設計基礎
Win32 視窗程式設計基礎Win32 視窗程式設計基礎
Win32 視窗程式設計基礎
 
Matlab 在機率與統計的應用
Matlab 在機率與統計的應用Matlab 在機率與統計的應用
Matlab 在機率與統計的應用
 
Android 2D 遊戲設計基礎
Android 2D 遊戲設計基礎Android 2D 遊戲設計基礎
Android 2D 遊戲設計基礎
 
Android 介面設計
Android 介面設計Android 介面設計
Android 介面設計
 
Java 視窗程式設計
Java 視窗程式設計Java 視窗程式設計
Java 視窗程式設計
 
Java 網路程式
Java 網路程式Java 網路程式
Java 網路程式
 
Android introduction
Android introductionAndroid introduction
Android introduction
 
RESTful
RESTfulRESTful
RESTful
 
Web service
Web serviceWeb service
Web service
 
How toprogram
How toprogramHow toprogram
How toprogram
 
Object-Based Programming Part II
Object-Based Programming Part IIObject-Based Programming Part II
Object-Based Programming Part II
 
Object-Based Programming Part One
Object-Based Programming Part OneObject-Based Programming Part One
Object-Based Programming Part One
 

Recently uploaded

Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
UiPathCommunity
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 

Recently uploaded (20)

Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 

Object-Oriented Programming

  • 1. Object-Oriented ProgrammingObject-Oriented Programming (( 物件導向程式設計物件導向程式設計 )) Lecturer: Liao Ping-Lun (Lecturer: Liao Ping-Lun ( 廖柄㷍廖柄㷍 )) EMail:EMail: pinglunliao@gmail.compinglunliao@gmail.com
  • 2. AgendaAgenda Project Complex classProject Complex class Project TStack with PersonProject TStack with Person Inheritance (Inheritance ( 繼承繼承 )) Polymorphism (Polymorphism ( 多型多型 ))
  • 3. Overloaded Operators (Overloaded Operators ( 運算子重載運算子重載 )) operator[] (subscript operator)operator[] (subscript operator) char city[40] = "Taipei";char city[40] = "Taipei"; cout << city[1] << endl; // display 'a'cout << city[1] << endl; // display 'a' String opera("The Duck");String opera("The Duck"); char& String::operator[](int)char& String::operator[](int) { return str[i]; } // opera[0] = 'T';{ return str[i]; } // opera[0] = 'T'; const char& String::operator[](int i) constconst char& String::operator[](int i) const { return str[i]; } // cout << opera[4];{ return str[i]; } // cout << opera[4]; // char ch = opera[3];// char ch = opera[3];
  • 4. Overloaded Operators (Overloaded Operators ( 運算子重載運算子重載 )) operator= (assignment operator)operator= (assignment operator) Person me;Person me; Person him = me; // not an assignmentPerson him = me; // not an assignment him = me; // assignmenthim = me; // assignment 為什麼是為什麼是 return by reference?return by reference? 因為修改的是自己因為修改的是自己
  • 5. Overloaded Operators (Overloaded Operators ( 運算子重載運算子重載 )) 重載重載 MyStackMyStack operator=operator= operator[]operator[]
  • 6. Project Complex ClassProject Complex Class Default ConstructorDefault Constructor With default valueWith default value Copy ConstructorCopy Constructor Operator overloadingOperator overloading operator+operator+ operator-operator- operator*operator* operator<<operator<< operator>>operator>> 示範示範 operator+operator+
  • 7. Project Complex ClassProject Complex Class SolutionSolution
  • 8. Pointer and objectPointer and object String glamour;String glamour; String *first = &glamour;String *first = &glamour; // assign object address// assign object address String *gleep = new String;String *gleep = new String; // default constructor// default constructor // invoke String(const char*) constructor// invoke String(const char*) constructor String *glop = new String("me me me");String *glop = new String("me me me"); // invoke String(const String&) constructor// invoke String(const String&) constructor String *favorite = new String(glamour);String *favorite = new String(glamour); if(glamour < *first)if(glamour < *first) // compare object value// compare object value
  • 9. Implicit and explicit type conversionImplicit and explicit type conversion class Stringclass String {{ //...//... explicit String( const char* pstr ); // str = String("ABC");explicit String( const char* pstr ); // str = String("ABC"); operator char*();operator char*(); };}; String str;String str; str = "TEST"; //Error: cannot convert "TEST" to String impstr = "TEST"; //Error: cannot convert "TEST" to String imp licitlylicitly char *pstr = str; // char *pstr = (char*)str;char *pstr = str; // char *pstr = (char*)str;
  • 10. InheritanceInheritance Is-a relationshipIs-a relationship Public inheritancePublic inheritance Initializer list in default constructorInitializer list in default constructor Virtual member functionVirtual member function Static binding and dynamic bindingStatic binding and dynamic binding Abstract base classAbstract base class Pure virtual functionPure virtual function Public interfacePublic interface
  • 11. Is-a & has-a relationshipsIs-a & has-a relationships 直線、矩形是圖形,但畫布上有好多圖形!直線、矩形是圖形,但畫布上有好多圖形!
  • 12. Inheriting classInheriting class Base classBase class Derived classDerived class
  • 13. Using Derived classUsing Derived class 跟在使用一般類別一樣的語法。跟在使用一般類別一樣的語法。
  • 15. Inheritance classInheritance class class RatedPlayerclass RatedPlayer: public: public TableTennisPlayerTableTennisPlayer {{ private:private: int rating;int rating; public:public: ...... };};
  • 16. Base and Derived Class ObjectBase and Derived Class Object
  • 17. Access specify without inheritanceAccess specify without inheritance
  • 18. Initilizer ListInitilizer List Derived classDerived class 設定設定 Base classBase class 的的 privateprivate member variablesmember variables 時時 RatedPlayer::RatedPlayer(unsigned int r, const charRatedPlayer::RatedPlayer(unsigned int r, const char * fn, const char * ln, bool ht) : TableTennisPlayer* fn, const char * ln, bool ht) : TableTennisPlayer (fn, ln, ht)(fn, ln, ht) {{ rating = r;rating = r; }} RatedPlayer rplayer1(1140, "Mallory", "Duck", true)RatedPlayer rplayer1(1140, "Mallory", "Duck", true) ;;
  • 19. Initilizer ListInitilizer List RatedPlayer::RatedPlayer(unsigned int r, const charRatedPlayer::RatedPlayer(unsigned int r, const char * fn, const char * ln, bool ht) : TableTennisPlayer* fn, const char * ln, bool ht) : TableTennisPlayer (fn, ln, ht), rating(r)(fn, ln, ht), rating(r) {}{} RatedPlayer rplayer1(1140, "Mallory", "Duck", true)RatedPlayer rplayer1(1140, "Mallory", "Duck", true) ;;
  • 20. Default constructor in derived classDefault constructor in derived class Completely constructors in base classCompletely constructors in base class Using initializer list to build up defaultUsing initializer list to build up default constructor in derived classconstructor in derived class Data members in initialization in derived clData members in initialization in derived cl assass
  • 21. Access specify with inheritanceAccess specify with inheritance
  • 22. Special relationship between base and derived classSpecial relationship between base and derived class Using base class methodUsing base class method Upward castingUpward casting Downward casting is not allowedDownward casting is not allowed
  • 23. Using base class methodUsing base class method RatedPlayer rplayer1(1140, "Mallory", "Duck", true);RatedPlayer rplayer1(1140, "Mallory", "Duck", true); rplayer1.Name();rplayer1.Name();// derived object uses base method// derived object uses base method
  • 24. Upward castingUpward casting RatedPlayer rplayer1(1140, "Mallory", "Duck", true);RatedPlayer rplayer1(1140, "Mallory", "Duck", true); TableTennisPlayer &rt = rplayer;TableTennisPlayer &rt = rplayer; TAbleTennisPlayer *pt = &rplayer;TAbleTennisPlayer *pt = &rplayer; rt.Name();rt.Name(); // invoke Name() with reference// invoke Name() with reference pt->Name();pt->Name(); // invoke Name() with pointer// invoke Name() with pointer
  • 25. Downward casting is not allowedDownward casting is not allowed TableTennisPlayer player("Tara", "Boomdea", false)TableTennisPlayer player("Tara", "Boomdea", false) ;; RatedPlayer &rrp = player;RatedPlayer &rrp = player; // not allowed// not allowed RatedPlayer *prp = &player;RatedPlayer *prp = &player; // not allowed// not allowed
  • 26. Implicit upward castingImplicit upward casting void method(void method(const Base_class &bcconst Base_class &bc);); void Show(const TableTennisPlayer &rt)void Show(const TableTennisPlayer &rt) {{ cout << "Name: ";cout << "Name: "; rt.Name();rt.Name(); cout << "nTable: ";cout << "nTable: "; if(rt.HasTable()) cout << "yesn";if(rt.HasTable()) cout << "yesn"; else cout << "non";else cout << "non"; }} TableTennisPlayer player1("Tara", "Boomdea", false);TableTennisPlayer player1("Tara", "Boomdea", false); RatedPlayer rplayer1(1140, "Mallory", "Duck", true);RatedPlayer rplayer1(1140, "Mallory", "Duck", true); Show(player1);Show(player1); Show(rplayer1);Show(rplayer1);
  • 27. Implicit copy constructorImplicit copy constructor RatedPlayer sams(1100, "Sams", "Lups", true);RatedPlayer sams(1100, "Sams", "Lups", true); // invoke implicit copy constructor and up-casting, TableTenn// invoke implicit copy constructor and up-casting, TableTenn isPlayer(const TableTennisPlayer&);isPlayer(const TableTennisPlayer&); TableTennisPlayer fakeSams1(sams);TableTennisPlayer fakeSams1(sams); TableTennisPlayer fakeSams2 = sams;TableTennisPlayer fakeSams2 = sams; TableTennisPlayer fakeSams3;TableTennisPlayer fakeSams3; fakeSams3 = sams;fakeSams3 = sams; // assignment op and up-casting// assignment op and up-casting
  • 28. Inheritance modelInheritance model PublicPublic Is-a relationshipIs-a relationship Illegal relationshipsIllegal relationships Is-like-a, has-a, is-implemented-as, uses-aIs-like-a, has-a, is-implemented-as, uses-a PrivatePrivate ProtectedProtected
  • 29. BindingBinding Static binding (early binding)Static binding (early binding) during compiliduring compili ngng Dynamic binding (late binding)Dynamic binding (late binding) during execduring exec utionution
  • 30. Type compatibility of pointer and referenceType compatibility of pointer and reference double x = 3.5;double x = 3.5; int *pi = &x;int *pi = &x; // mismatch pointer types// mismatch pointer types long &r = x;long &r = x; // mismatch reference type// mismatch reference type DerivedClass test;DerivedClass test; BaseClass *pd = &test; // okBaseClass *pd = &test; // ok BaseClass &rd = test; // okBaseClass &rd = test; // ok
  • 31. Upward & downward castingUpward & downward casting class Singer: public Employeeclass Singer: public Employee {{ public:public: void range();void range(); };}; class Employeeclass Employee {{ private:private: char name[40];char name[40]; public:public: void show_name();void show_name(); };}; Employee veep;Employee veep; Singer trala;Singer trala; Employee *pe = &trala;Employee *pe = &trala; // upward casting// upward casting Singer *ps = (Singer*)&veep;Singer *ps = (Singer*)&veep; // downward casting// downward casting pe->show_name();pe->show_name(); // ok// ok pe->range();pe->range(); // compile error: range() is not a member of Employee// compile error: range() is not a member of Employee ps->range();ps->range(); // Run time error// Run time error
  • 32. Upward & downward castingUpward & downward casting Why ?Why ? downward casting: run time error.downward casting: run time error. upward casting: compile error.upward casting: compile error.
  • 33. Virtual member function & dynamic bindingVirtual member function & dynamic binding Virtual function uses dynamic binding, whereas,Virtual function uses dynamic binding, whereas, non-virtual function employs static bindingnon-virtual function employs static binding Derived_class dc;Derived_class dc; // derived class// derived class Base_class *bcp;Base_class *bcp; // base class// base class bcp = &dc;bcp = &dc; // Base_class pointer to Derived_class object// Base_class pointer to Derived_class object bcp->Function();bcp->Function(); // which version?// which version?
  • 34. Virtual member function & dynamic bindingVirtual member function & dynamic binding ExampleExample Brass Porky("Porcelot Pigg", 381299, 4000.00);Brass Porky("Porcelot Pigg", 381299, 4000.00); Brass *bp; // base classBrass *bp; // base class bp = &Porky;bp = &Porky; bp->ViewAcct(); // which version?bp->ViewAcct(); // which version?
  • 35. Virtual or non-virtual?Virtual or non-virtual? Virtual functionVirtual function Base class member functionBase class member function isis allowedallowed to be rto be r edefinededefined in derived classin derived class Non-virtual functionNon-virtual function Base class member functionBase class member function isis not allowednot allowed toto bebe redefined in derived classredefined in derived class
  • 36. How virtual function work?How virtual function work? ExampleExample Instrument4.cppInstrument4.cpp
  • 37. How virtual function work?How virtual function work? *Virtual function table (vtbl)*Virtual function table (vtbl) Single ObjectSingle Object
  • 38. How virtual function work?How virtual function work? *Virtual function table (vtbl)*Virtual function table (vtbl) Multiple ObjectMultiple Object
  • 39. Price for using virtual functionPrice for using virtual function Extra vtbl space using for every object creExtra vtbl space using for every object cre ationation Compiler will create an array to store virtuaCompiler will create an array to store virtua l function address in every classl function address in every class Extra time using in finding the function addExtra time using in finding the function add ressress
  • 40. Rules for virtual functionRules for virtual function Constructor cannot be a virtual functionConstructor cannot be a virtual function Destructor usually be a virtual functionDestructor usually be a virtual function Friend function cannot be a virtual functionFriend function cannot be a virtual function Static function cannot be a virtual functionStatic function cannot be a virtual function Function signature consistence in a redefinFunction signature consistence in a redefin ed functioned function If virtual functions are overloaded in base cIf virtual functions are overloaded in base c lass, then redefined all the functions in derilass, then redefined all the functions in deri ved classved class
  • 42. Member functions in classMember functions in class
  • 44. ReferencesReferences Thinking in C++ (Free E-Book)Thinking in C++ (Free E-Book) Beginning C++: The Complete LanguageBeginning C++: The Complete Language (( 中譯:中譯: C++C++ 教學範本教學範本 )) 物件導向程式設計物件導向程式設計 hh ttp://vr.me.ncku.edu.tw/courses/index-oop.htmttp://vr.me.ncku.edu.tw/courses/index-oop.htm 良葛格學習筆記良葛格學習筆記 httphttp ://caterpillar.onlyfun.net/Gossip/index.html://caterpillar.onlyfun.net/Gossip/index.html