SlideShare a Scribd company logo
Data Structures and
Algorithms in C++
Michael T. Goodrich Roberto Tamassia David M. Mount
Chapter 2
Object-Oriented Design
Contents
• 2.1 Goals and Principles
• 2.2 Inheritance and Polymorphism
• 2.3 Templates
• 2.4 Exceptions
• 2.5 Recursion and Other Design Patterns
• 2.6 Exercises
2.1 Goals and Principles
• Goals
Robustness
Adaptability
Reusability
• Principles
Abstraction
Encapsulation
Modularity
2.2 Inheritance and Polymorphism
2.2.1 Inheritance in C++
class Person {
private:
string name;
string ssn;
public:
//…
void print();
string getName();
};
2.2 Inheritance and Polymorphism
class Student : public Person {
private:
string major;
int gradYear;
public:
//…
void print();
void changeMajor( string newMajor);
};
2.2 Inheritance and Polymorphism
Member Functions
void Person::print() {
cout << “Name “ << name << ‘n’;
cout << “SSN “ << ssn << ‘n’;
}
void Student::print() {
Person::print();
cout << “Major “ << major << ‘n’;
cout << “Year “ << gradYear << ‘n’;
}
2.2 Inheritance and Polymorphism
Protected Members
class <class_name> {
private:
//…
protected:
//…
public:
//…
};
2.2 Inheritance and Polymorphism
Constructors and Destructors
Person::Person(const string &nm, const string &ss)
: name(nm), // initialize name
ssn(ss) { } // initialize ssn
Student::Student(const string &nm, const string &ss,
const string &maj, int year)
: Person(nm, ss), // initialize Person members
major(maj), // initialize member
gradYear(year) { } // initialize graduation year
Student* s = new Student(“John Smith”,”123-45-6789”,”Physics”,2010);
Person::~Person() //Person destructor
{…}
Student::~Student() //Student destructor
{…}
delete s; //calls ~Student() then ~Person()
2.2 Inheritance and Polymorphism
Static Binding
Person* pp[100];
pp[0] = new Person(…);
pp[1] = new Student(…);
cout << pp[1] ->getName() <<‘n’; //okay
pp[0] ->print();
pp[1] ->print();
pp[1] ->changeMajor(“English”); //ERROR!
2.2 Inheritance and Polymorphism
Dynamic Binding and Virtual Functions
class Person {
virtual void print() {….}
//…
};
class Student : public Person {
virtual void print() {….}
//…
};
2.2 Inheritance and Polymorphism
2.2.3 Examples of Inheritance in C++
2.2 Inheritance and Polymorphism
Arithmetic and Geometric Progression Classes
2.2 Inheritance and Polymorphism
A Fibonacci Progression Class
2.2 Inheritance and Polymorphism
2.2 Inheritance and Polymorphism
2.2.4 Multiple Inheritance and Class Casting
class Base {
protected: int foo;
public: int bar;
};
class Derive1 : public Base {
//foo is protected and bar is public
};
class Derive2 : protected Base {
//both foo and bar are protected
};
class Derive3 : private Base {
// both foo and bar are private
};
2.2 Inheritance and Polymorphism
2.2.5 Interfaces and Abstract Classes
class Stack {
public:
bool isEmpty( ) const;
void push(int x);
int pop( );
};
2.2 Inheritance and Polymorphism
Interfaces and Abstract Base Classes
class Stack {
public:
virtual bool isEmpty( ) const = 0;
virtual void push(int x) = 0;
virtual int pop( ) = 0;
};
class ConcreteStack : public Stack {
pribate: //….
public:
virtual bool isEmpty( ) {…}
virtual void push(int x) {…}
virtual int pop( ) {…}
};
2.3 Templates
2.3.1 Function Templates
int min(int a, int b)
{ return (a < b ? a : b); }
template <typename T>
T min( T a, T b)
{ return (a < b ? a : b); }
2.3 Templates
2.3.2 Class Templates
template <typename Object>
class BasicVector {
Object* a;
int capacity;
public:
BasicVector(int capac = 10) {
capacity = capac;
a = new Object[ capacity ];
}
Object& elemAtRank(int r)
{ return a[r]; }
//…
};
2.3 Templates
2.3.2 Class Templates
BasicVector<int> iv(5);
BasicVector<double> dv(20);
BasicVector<string> sv(10);
//…
iv. elemAtRank(3) = 8;
dv. elemAtRank(14) = 2.5;
sv. elemAtRank(7) = “hello”;
2.3 Templates
Templated Arguments
BasicVector<BasicVector<int> > xv(5);
//…
xv. elemAtRank(2). elemAtRank(8) = 15;
Templated Members
template <typename Object>
Object& BasicVector<Object>::elemAtRank(int r) {
return a[r];
}
2.4 Exceptions
2.4.1 Exceptions Object
class MathException {
private:
string errMsg;
public:
MathException(const string& err)
{ errMsg = err; }
};
2.4 Exceptions
Using Inheritance to Define New Exception Types
class ZeroDivideException : public MathException {
public:
ZeroDivideException(const string& err)
: MathException(err) { }
};
class NegativeRootException : public MathException {
public:
NegativeRootException(const string& err)
: MathException(err) { }
};
2.4 Exceptions
2.4.2 Throwing and Catching Exceptions
try {
if (divisor == 0 )
throw ZeroDivideException(“Divide by zero in
Module X”);
}
catch (ZeroDivideException& zde) {
//…
}
catch (MathException& me) {
//…
}
2.4 Exceptions
2.4.3 Exceptions Specification
void calculator( ) throw(ZeroDivideException,
NegativeRootException ) {
//function body…
}
2.4 Exceptions
Generic Exception Class
class RuntimeException {
private:
string errorMsg;
public:
RuntimeException( const string& err)
{errorMsg = err; }
string getMessage() const { return errorMsh; }
};
inline std::ostream& operator <<(std::ostream& out,
const RuntimeException& e)
{ return out << e.getMessage(); }
2.5 Recursion and Other Design Patterns
int recursiveFactorial(int n) {
if (n==0) return 1;
else return n*recursiveFactorial(n-1);
}
2.6 Exercises
• R-2.11
• R-2.12

More Related Content

Similar to vdocument.in_data-structures-and-algorithms-in-c-michael-t-goodrich-roberto-tamassia-5689cfa959a68.ppt

Inheritance_with_its_types_single_multi_hybrid
Inheritance_with_its_types_single_multi_hybridInheritance_with_its_types_single_multi_hybrid
Inheritance_with_its_types_single_multi_hybrid
VGaneshKarthikeyan
 
Object Oriented Programming using C++: Ch09 Inheritance.pptx
Object Oriented Programming using C++: Ch09 Inheritance.pptxObject Oriented Programming using C++: Ch09 Inheritance.pptx
Object Oriented Programming using C++: Ch09 Inheritance.pptx
RashidFaridChishti
 
Inheritance
InheritanceInheritance
Inheritance
Burhan Ahmed
 
Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Refactoring - improving the smell of your code
Refactoring - improving the smell of your codeRefactoring - improving the smell of your code
Refactoring - improving the smell of your codevmandrychenko
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing Scenario
Tara Hardin
 
Enhancing Productivity and Insight A Tour of JDK Tools Progress Beyond Java 17
Enhancing Productivity and Insight  A Tour of JDK Tools Progress Beyond Java 17Enhancing Productivity and Insight  A Tour of JDK Tools Progress Beyond Java 17
Enhancing Productivity and Insight A Tour of JDK Tools Progress Beyond Java 17
Ana-Maria Mihalceanu
 
Inheritance
InheritanceInheritance
Inheritance
GowriLatha1
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
Daniel Waligóra
 
C++ Classes Tutorials.ppt
C++ Classes Tutorials.pptC++ Classes Tutorials.ppt
C++ Classes Tutorials.ppt
aasuran
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 InheritanceAmrit Kaur
 
Csphtp1 10
Csphtp1 10Csphtp1 10
Csphtp1 10
HUST
 
3433 Ch10 Ppt
3433 Ch10 Ppt3433 Ch10 Ppt
3433 Ch10 Ppt
martha leon
 
OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++
Dev Chauhan
 
麻省理工C++公开教学课程(三)
麻省理工C++公开教学课程(三)麻省理工C++公开教学课程(三)
麻省理工C++公开教学课程(三)
ProCharm
 
麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)ProCharm
 
Doctrine and NoSQL
Doctrine and NoSQLDoctrine and NoSQL
Doctrine and NoSQL
Benjamin Eberlei
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
Renas Rekany
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsFALLEE31188
 
Doctrine for NoSQL
Doctrine for NoSQLDoctrine for NoSQL
Doctrine for NoSQL
Benjamin Eberlei
 

Similar to vdocument.in_data-structures-and-algorithms-in-c-michael-t-goodrich-roberto-tamassia-5689cfa959a68.ppt (20)

Inheritance_with_its_types_single_multi_hybrid
Inheritance_with_its_types_single_multi_hybridInheritance_with_its_types_single_multi_hybrid
Inheritance_with_its_types_single_multi_hybrid
 
Object Oriented Programming using C++: Ch09 Inheritance.pptx
Object Oriented Programming using C++: Ch09 Inheritance.pptxObject Oriented Programming using C++: Ch09 Inheritance.pptx
Object Oriented Programming using C++: Ch09 Inheritance.pptx
 
Inheritance
InheritanceInheritance
Inheritance
 
Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2
 
Refactoring - improving the smell of your code
Refactoring - improving the smell of your codeRefactoring - improving the smell of your code
Refactoring - improving the smell of your code
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing Scenario
 
Enhancing Productivity and Insight A Tour of JDK Tools Progress Beyond Java 17
Enhancing Productivity and Insight  A Tour of JDK Tools Progress Beyond Java 17Enhancing Productivity and Insight  A Tour of JDK Tools Progress Beyond Java 17
Enhancing Productivity and Insight A Tour of JDK Tools Progress Beyond Java 17
 
Inheritance
InheritanceInheritance
Inheritance
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
C++ Classes Tutorials.ppt
C++ Classes Tutorials.pptC++ Classes Tutorials.ppt
C++ Classes Tutorials.ppt
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
 
Csphtp1 10
Csphtp1 10Csphtp1 10
Csphtp1 10
 
3433 Ch10 Ppt
3433 Ch10 Ppt3433 Ch10 Ppt
3433 Ch10 Ppt
 
OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++
 
麻省理工C++公开教学课程(三)
麻省理工C++公开教学课程(三)麻省理工C++公开教学课程(三)
麻省理工C++公开教学课程(三)
 
麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)
 
Doctrine and NoSQL
Doctrine and NoSQLDoctrine and NoSQL
Doctrine and NoSQL
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Doctrine for NoSQL
Doctrine for NoSQLDoctrine for NoSQL
Doctrine for NoSQL
 

Recently uploaded

Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
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
 
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
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
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
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
ViralQR
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
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
 
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
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
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
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
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
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
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
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 

Recently uploaded (20)

Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.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
 
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
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
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 -...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
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...
 
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
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
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)
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
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
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
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...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 

vdocument.in_data-structures-and-algorithms-in-c-michael-t-goodrich-roberto-tamassia-5689cfa959a68.ppt

  • 1. Data Structures and Algorithms in C++ Michael T. Goodrich Roberto Tamassia David M. Mount Chapter 2 Object-Oriented Design
  • 2. Contents • 2.1 Goals and Principles • 2.2 Inheritance and Polymorphism • 2.3 Templates • 2.4 Exceptions • 2.5 Recursion and Other Design Patterns • 2.6 Exercises
  • 3. 2.1 Goals and Principles • Goals Robustness Adaptability Reusability • Principles Abstraction Encapsulation Modularity
  • 4. 2.2 Inheritance and Polymorphism 2.2.1 Inheritance in C++ class Person { private: string name; string ssn; public: //… void print(); string getName(); };
  • 5. 2.2 Inheritance and Polymorphism class Student : public Person { private: string major; int gradYear; public: //… void print(); void changeMajor( string newMajor); };
  • 6. 2.2 Inheritance and Polymorphism Member Functions void Person::print() { cout << “Name “ << name << ‘n’; cout << “SSN “ << ssn << ‘n’; } void Student::print() { Person::print(); cout << “Major “ << major << ‘n’; cout << “Year “ << gradYear << ‘n’; }
  • 7. 2.2 Inheritance and Polymorphism Protected Members class <class_name> { private: //… protected: //… public: //… };
  • 8. 2.2 Inheritance and Polymorphism Constructors and Destructors Person::Person(const string &nm, const string &ss) : name(nm), // initialize name ssn(ss) { } // initialize ssn Student::Student(const string &nm, const string &ss, const string &maj, int year) : Person(nm, ss), // initialize Person members major(maj), // initialize member gradYear(year) { } // initialize graduation year Student* s = new Student(“John Smith”,”123-45-6789”,”Physics”,2010); Person::~Person() //Person destructor {…} Student::~Student() //Student destructor {…} delete s; //calls ~Student() then ~Person()
  • 9. 2.2 Inheritance and Polymorphism Static Binding Person* pp[100]; pp[0] = new Person(…); pp[1] = new Student(…); cout << pp[1] ->getName() <<‘n’; //okay pp[0] ->print(); pp[1] ->print(); pp[1] ->changeMajor(“English”); //ERROR!
  • 10. 2.2 Inheritance and Polymorphism Dynamic Binding and Virtual Functions class Person { virtual void print() {….} //… }; class Student : public Person { virtual void print() {….} //… };
  • 11. 2.2 Inheritance and Polymorphism 2.2.3 Examples of Inheritance in C++
  • 12. 2.2 Inheritance and Polymorphism Arithmetic and Geometric Progression Classes
  • 13. 2.2 Inheritance and Polymorphism A Fibonacci Progression Class
  • 14. 2.2 Inheritance and Polymorphism
  • 15. 2.2 Inheritance and Polymorphism 2.2.4 Multiple Inheritance and Class Casting class Base { protected: int foo; public: int bar; }; class Derive1 : public Base { //foo is protected and bar is public }; class Derive2 : protected Base { //both foo and bar are protected }; class Derive3 : private Base { // both foo and bar are private };
  • 16. 2.2 Inheritance and Polymorphism 2.2.5 Interfaces and Abstract Classes class Stack { public: bool isEmpty( ) const; void push(int x); int pop( ); };
  • 17. 2.2 Inheritance and Polymorphism Interfaces and Abstract Base Classes class Stack { public: virtual bool isEmpty( ) const = 0; virtual void push(int x) = 0; virtual int pop( ) = 0; }; class ConcreteStack : public Stack { pribate: //…. public: virtual bool isEmpty( ) {…} virtual void push(int x) {…} virtual int pop( ) {…} };
  • 18. 2.3 Templates 2.3.1 Function Templates int min(int a, int b) { return (a < b ? a : b); } template <typename T> T min( T a, T b) { return (a < b ? a : b); }
  • 19. 2.3 Templates 2.3.2 Class Templates template <typename Object> class BasicVector { Object* a; int capacity; public: BasicVector(int capac = 10) { capacity = capac; a = new Object[ capacity ]; } Object& elemAtRank(int r) { return a[r]; } //… };
  • 20. 2.3 Templates 2.3.2 Class Templates BasicVector<int> iv(5); BasicVector<double> dv(20); BasicVector<string> sv(10); //… iv. elemAtRank(3) = 8; dv. elemAtRank(14) = 2.5; sv. elemAtRank(7) = “hello”;
  • 21. 2.3 Templates Templated Arguments BasicVector<BasicVector<int> > xv(5); //… xv. elemAtRank(2). elemAtRank(8) = 15; Templated Members template <typename Object> Object& BasicVector<Object>::elemAtRank(int r) { return a[r]; }
  • 22. 2.4 Exceptions 2.4.1 Exceptions Object class MathException { private: string errMsg; public: MathException(const string& err) { errMsg = err; } };
  • 23. 2.4 Exceptions Using Inheritance to Define New Exception Types class ZeroDivideException : public MathException { public: ZeroDivideException(const string& err) : MathException(err) { } }; class NegativeRootException : public MathException { public: NegativeRootException(const string& err) : MathException(err) { } };
  • 24. 2.4 Exceptions 2.4.2 Throwing and Catching Exceptions try { if (divisor == 0 ) throw ZeroDivideException(“Divide by zero in Module X”); } catch (ZeroDivideException& zde) { //… } catch (MathException& me) { //… }
  • 25. 2.4 Exceptions 2.4.3 Exceptions Specification void calculator( ) throw(ZeroDivideException, NegativeRootException ) { //function body… }
  • 26. 2.4 Exceptions Generic Exception Class class RuntimeException { private: string errorMsg; public: RuntimeException( const string& err) {errorMsg = err; } string getMessage() const { return errorMsh; } }; inline std::ostream& operator <<(std::ostream& out, const RuntimeException& e) { return out << e.getMessage(); }
  • 27. 2.5 Recursion and Other Design Patterns int recursiveFactorial(int n) { if (n==0) return 1; else return n*recursiveFactorial(n-1); }