SlideShare a Scribd company logo
1 of 23
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
1
More about OOP and ADTs
Classes
Chapter 4
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
2
Chapter Contents
4.1 Procedural vs. Object-Oriented
Programming
4.2 Classes
4.3 Example: A First Version of a User-
Defined Time Class
4.4 Class Constructors
4.5 Other Class Operators
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
3
Chapter Objectives
• Contrast OOP with procedural programming
• Review classes in C++
• Study in detail a specific example of how a class is
built
• Show how operators can be overloaded for new
types
• Show how conditional compilation directives are
used to avoid redundant declarations
• Discuss pointers to class objects – the this
pointer, in particular
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
4
Contrast Procedural, Object Oriented Paradigms
Procedural
• Action-oriented — concentrates
on the verbs
• Programmers:
– Identify basic tasks to solve
problem
– Implement actions to do tasks
as subprograms
(procedures/functions/
subroutines)
– Group subprograms into
programs/modules/libraries,
– together make up a complete
system for solving the problem
Object-oriented
• Focuses on the nouns of problem
specification
• Programmers:
– Determine objects needed for
problem
– Determine how they should
work together to solve the
problem.
– Create types called classes
made up of
• data members
• function members to operate
on the data.
– Instances of a type (class)
called objects.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
5
Structs and Classes
Similarities
• Essentially the same syntax
• Both are used to model objects with multiple
attributes (characteristics)
– represented as data members
– also called fields … or …
– instance or attribute variables).
• Thus, both are used to process non-
homogeneous data sets.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
6
Structs vs. Classes
Differences
• No classes in C
• Members public by
default
• Can be specified
private
• Both structs and
classes in C++
• Structs can have
members declared
private
• Class members are
private by default
• Can be specified public
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
7
Advantages in C++
(structs and Classes)
• C++ structs and classes model objects
which have:
– Attributes represented as data members
– Operations represented as functions (or
methods)
• Leads to object oriented programming
– Objects are self contained
– "I can do it myself" mentality
– They do not pass a parameter to an external
function
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
8
Class Declaration
• Syntax
class ClassName
{
public:
Declarations of public members
private:
Declarations of private members
};
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
9
Designing a Class
• Data members normally placed in private:
section of a class
• Function members usually in public: section
• Typically public: section followed by private:
– although not required by compiler
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
10
Class Libraries
• Class declarations placed in header file
– Given .h extension
– Contains data items and prototypes
• Implementation file
– Same prefix name as header file
– Given .cpp extension
• Programs which use this class library called
client programs
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
11
Translating a Library
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
12
Example of User-Defined
Time Class
• Recall Time struct from previous chapter
– Actions done to Time object required use of Time
parameter in the functions
• Now we create a Time class
– Actions done to Time object, done by the object itself
• Note interface for Time class object,
Fig. 4.2
– Data members private – inaccessible to users of the
class
– Information hiding
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
13
Constructors
• Note constructor definition in Time.cpp
example
• Syntax
ClassName::ClassName (parameter_list)
: member_initializer_list
{
// body of constructor definition
}
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
14
Constructors
• Results of default constructor
• Results of explicit-value
constructor
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
15
Overloading Functions
• Note existence of multiple functions with the
same name
Time();
Time(unsigned initHours,
unsigned initMinutes,
char initAMPM);
– Known as overloading
• Compiler compares numbers and types of
arguments of overloaded functions
– Checks the "signature" of the functions
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
16
Default Arguments
• Possible to specify default values for
constructor arguments
Time(unsigned initHours = 12,
unsigned initMinutes = 0,
char initAMPM = 'A');
• Consider
Time t1, t2(5), t3(6,30), t4(8,15,'P');
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
17
Copy Operations
• During initialization
Time t = bedTime
• During Assignment
t = midnight;
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
18
Redundant Declarations
• Note use of #include "Time.h" in
– Time.cpp
– Client program
• Causes "redeclaration" errors at compile
time
• Solution is to use conditional compilation
– Use #ifndef and #define and #endif compiler
directives
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
19
Pointers to Class Objects
• Possible to declare pointers to class objects
Time * timePtr = &t;
• Access with
timePtr->getMilTime() or
(*timePtr).getMilTime()
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
20
The this Pointer
• Every class has a keyword, this
– a pointer whose value is the address of the
object
– Value of *this would be the object itself
Example
• #include<iostream>
• using namespace std;
• class Student
• {
• public:
• int ID;
• void GetID(int Index) //Reads the ID from the User
• {
• cout<<"ID "<<Index<<" : ";
• cin>>ID;
• }
• int Compare(int OtherID) //Compares the Student's ID with another one
• {
• if(ID > OtherID)
• return 1;
• else if ( ID < OtherID)
• return -1;
• else
• return 0; //IDs are equal
• }
• };
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition,
© 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3
21
• void main()
• {
• int StudentsNumber;
• Student* Students;
• cout << "Enter the Number of Students : ";
• cin >> StudentsNumber;
• cout<<endl;
• //Create dynamic array of students
• Students = new Student[StudentsNumber];
• for(int i=0 ; i<StudentsNumber ; i++)
• {
• Students[i].GetID(i+1);
• }
•
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
22
• //Sorting
• for(i=0 ; i<StudentsNumber; i++)
• {
• int Min=Students[i].ID;
• int Index = i;
• for(int j=i; j<StudentsNumber; j++)
• {
• if(Students[j].Compare(Min) == -1)
• {
• Min = Students[j].ID;
• Index = j;
• }
• }
• //Swap
• Student Temp = Students[i];
• Students[i] = Students[Index];
• Students[Index] = Temp;
• }
• //Display the sorted IDs
• cout<<"nSorted Students IDs are : n";
• for(i=0; i<StudentsNumber ; i++)
• cout<<Students[i].ID<<endl;
• }
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson
Education, Inc. All rights reserved. 0-13-140909-3
23

More Related Content

Similar to Lec4 (20)

Lec5
Lec5Lec5
Lec5
 
C++ Basics
C++ BasicsC++ Basics
C++ Basics
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
Introduction to oop
Introduction to oop Introduction to oop
Introduction to oop
 
Lec3
Lec3Lec3
Lec3
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
C++ programming intro
C++ programming introC++ programming intro
C++ programming intro
 
Lecture1
Lecture1Lecture1
Lecture1
 
Fundamentals of Programming in C++.ppt
Fundamentals of Programming in C++.pptFundamentals of Programming in C++.ppt
Fundamentals of Programming in C++.ppt
 
cs8251 unit 1 ppt
cs8251 unit 1 pptcs8251 unit 1 ppt
cs8251 unit 1 ppt
 
C++ppt. Classs and object, class and object
C++ppt. Classs and object, class and objectC++ppt. Classs and object, class and object
C++ppt. Classs and object, class and object
 
Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1
 
C chap16
C chap16C chap16
C chap16
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
 
c++ ppt.ppt
c++ ppt.pptc++ ppt.ppt
c++ ppt.ppt
 
UsingCPP_for_Artist.ppt
UsingCPP_for_Artist.pptUsingCPP_for_Artist.ppt
UsingCPP_for_Artist.ppt
 

More from Ibrahim El-Torbany (12)

C++ examples &revisions
C++ examples &revisionsC++ examples &revisions
C++ examples &revisions
 
Lec6 mod linked list
Lec6 mod linked listLec6 mod linked list
Lec6 mod linked list
 
Lec2
Lec2Lec2
Lec2
 
Lec2&3 data structure
Lec2&3 data structureLec2&3 data structure
Lec2&3 data structure
 
Lec1
Lec1Lec1
Lec1
 
Ass logic
Ass logicAss logic
Ass logic
 
Math lecture 4 Part 1
Math lecture 4 Part 1Math lecture 4 Part 1
Math lecture 4 Part 1
 
Tutorial 1
Tutorial 1Tutorial 1
Tutorial 1
 
Lec2&3_DataStructure
Lec2&3_DataStructureLec2&3_DataStructure
Lec2&3_DataStructure
 
Lecture 2 math 2
Lecture 2 math 2Lecture 2 math 2
Lecture 2 math 2
 
Lec1
Lec1Lec1
Lec1
 
Chapter 1 what is statistics
Chapter 1 what is statisticsChapter 1 what is statistics
Chapter 1 what is statistics
 

Recently uploaded

Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 

Recently uploaded (20)

Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 

Lec4

  • 1. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 1 More about OOP and ADTs Classes Chapter 4
  • 2. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 2 Chapter Contents 4.1 Procedural vs. Object-Oriented Programming 4.2 Classes 4.3 Example: A First Version of a User- Defined Time Class 4.4 Class Constructors 4.5 Other Class Operators
  • 3. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 3 Chapter Objectives • Contrast OOP with procedural programming • Review classes in C++ • Study in detail a specific example of how a class is built • Show how operators can be overloaded for new types • Show how conditional compilation directives are used to avoid redundant declarations • Discuss pointers to class objects – the this pointer, in particular
  • 4. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 4 Contrast Procedural, Object Oriented Paradigms Procedural • Action-oriented — concentrates on the verbs • Programmers: – Identify basic tasks to solve problem – Implement actions to do tasks as subprograms (procedures/functions/ subroutines) – Group subprograms into programs/modules/libraries, – together make up a complete system for solving the problem Object-oriented • Focuses on the nouns of problem specification • Programmers: – Determine objects needed for problem – Determine how they should work together to solve the problem. – Create types called classes made up of • data members • function members to operate on the data. – Instances of a type (class) called objects.
  • 5. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 5 Structs and Classes Similarities • Essentially the same syntax • Both are used to model objects with multiple attributes (characteristics) – represented as data members – also called fields … or … – instance or attribute variables). • Thus, both are used to process non- homogeneous data sets.
  • 6. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 6 Structs vs. Classes Differences • No classes in C • Members public by default • Can be specified private • Both structs and classes in C++ • Structs can have members declared private • Class members are private by default • Can be specified public
  • 7. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 7 Advantages in C++ (structs and Classes) • C++ structs and classes model objects which have: – Attributes represented as data members – Operations represented as functions (or methods) • Leads to object oriented programming – Objects are self contained – "I can do it myself" mentality – They do not pass a parameter to an external function
  • 8. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 8 Class Declaration • Syntax class ClassName { public: Declarations of public members private: Declarations of private members };
  • 9. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 9 Designing a Class • Data members normally placed in private: section of a class • Function members usually in public: section • Typically public: section followed by private: – although not required by compiler
  • 10. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 10 Class Libraries • Class declarations placed in header file – Given .h extension – Contains data items and prototypes • Implementation file – Same prefix name as header file – Given .cpp extension • Programs which use this class library called client programs
  • 11. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 11 Translating a Library
  • 12. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 12 Example of User-Defined Time Class • Recall Time struct from previous chapter – Actions done to Time object required use of Time parameter in the functions • Now we create a Time class – Actions done to Time object, done by the object itself • Note interface for Time class object, Fig. 4.2 – Data members private – inaccessible to users of the class – Information hiding
  • 13. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 13 Constructors • Note constructor definition in Time.cpp example • Syntax ClassName::ClassName (parameter_list) : member_initializer_list { // body of constructor definition }
  • 14. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 14 Constructors • Results of default constructor • Results of explicit-value constructor
  • 15. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 15 Overloading Functions • Note existence of multiple functions with the same name Time(); Time(unsigned initHours, unsigned initMinutes, char initAMPM); – Known as overloading • Compiler compares numbers and types of arguments of overloaded functions – Checks the "signature" of the functions
  • 16. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 16 Default Arguments • Possible to specify default values for constructor arguments Time(unsigned initHours = 12, unsigned initMinutes = 0, char initAMPM = 'A'); • Consider Time t1, t2(5), t3(6,30), t4(8,15,'P');
  • 17. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 17 Copy Operations • During initialization Time t = bedTime • During Assignment t = midnight;
  • 18. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 18 Redundant Declarations • Note use of #include "Time.h" in – Time.cpp – Client program • Causes "redeclaration" errors at compile time • Solution is to use conditional compilation – Use #ifndef and #define and #endif compiler directives
  • 19. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 19 Pointers to Class Objects • Possible to declare pointers to class objects Time * timePtr = &t; • Access with timePtr->getMilTime() or (*timePtr).getMilTime()
  • 20. Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 20 The this Pointer • Every class has a keyword, this – a pointer whose value is the address of the object – Value of *this would be the object itself
  • 21. Example • #include<iostream> • using namespace std; • class Student • { • public: • int ID; • void GetID(int Index) //Reads the ID from the User • { • cout<<"ID "<<Index<<" : "; • cin>>ID; • } • int Compare(int OtherID) //Compares the Student's ID with another one • { • if(ID > OtherID) • return 1; • else if ( ID < OtherID) • return -1; • else • return 0; //IDs are equal • } • }; Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 21
  • 22. • void main() • { • int StudentsNumber; • Student* Students; • cout << "Enter the Number of Students : "; • cin >> StudentsNumber; • cout<<endl; • //Create dynamic array of students • Students = new Student[StudentsNumber]; • for(int i=0 ; i<StudentsNumber ; i++) • { • Students[i].GetID(i+1); • } • Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 22
  • 23. • //Sorting • for(i=0 ; i<StudentsNumber; i++) • { • int Min=Students[i].ID; • int Index = i; • for(int j=i; j<StudentsNumber; j++) • { • if(Students[j].Compare(Min) == -1) • { • Min = Students[j].ID; • Index = j; • } • } • //Swap • Student Temp = Students[i]; • Students[i] = Students[Index]; • Students[Index] = Temp; • } • //Display the sorted IDs • cout<<"nSorted Students IDs are : n"; • for(i=0; i<StudentsNumber ; i++) • cout<<Students[i].ID<<endl; • } Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 23