SlideShare a Scribd company logo
1 of 36
Download to read offline
Abstract Data Types (ADT)
and C++ Classes
1-15-2013
 Abstract Data Types (ADT) & UML
 C++ Class definition & implementation
 constructors, accessors & modifiers
 overloading operators
 friend functions
HW#1 posted – due: Tuesday, 1/22
Quiz Thursday, 1/24
 FAQ 5.14 What is an abstraction and why is it
important?
 FAQ 5.15 Should abstractions be user-centric or
developer-centric?
An abstraction is a simplified vew of an object
in the user’s own vocabulary. In OO and C++,
an abstraction is the simplest interface to an
object that provides all the features and
services the intended users expect.
User-centric. Focus on the user’s point of view.
 Computes what each employee should be paid for
a day of work. Reads a file containing start and
stop times for each employee. Then calculates and
saves the pay amounts to another file.
int runPayCalculator (const char csInputFileName[],
const char csOutputFileName[])
Sample input:
510 + 24601
990 - 24601
Sample output
24601 96
int runPayCalculator (const char csInputFileName[],
const char csOutputFileName[])
Algorithm:
call computeHours and then computeAndWritePay
Data structure:
The number of hours worked by each employee is
stored in an array indexed by the possible employee
numbers. This array is of size MAX_EMPLOYEE_NUMBER
+ 1, where MAX_EMPLOYEE_NUMBER is a global
constant
In a well-designed modular program, software
components should satisfy the following two
properties:
1. Each component performs one well-defined
task. (i.e. “cohesion”)
2. Each component is as independent as
possible from the others. (i.e. loosely
coupled”)
1. Easier to understand; little redundant code.
2. Facilitates software reuse.
3. Easier to implement.
4. Easier to test.
5. Easier to modify.
 Independence of modules is typically achieved by
“information hiding” (which can be achieved by
“encapsulation”).
 Procedural Abstraction
 Use of a function depends on its purpose (what it
does) but not on its implementation (how it does it).
 FAQ 5.18 What’s the value of separating
interface from implementation?
It’s a key to eliminating the ripple effect when a
change is made.
 Class designer/implementer
- designs & implements a class
vs.
 Client programmer
- uses a class for an application
vs.
 End-user
- uses the application
 Procedural Abstraction (Algorithm)
 Data Abstraction (Data)
 An Abstract Data Type (ADT) is a specification of
a set of data and a set of operations that can be
performed on the data.
examples:
String Circle
List Dice
Dictionary Song
Student Telephone Directory
Time Complex number
 In C++, a class represents an ADT.
 An “instance” of a class is a specific object which is
created, and the data members are filled in with
values (possibly default values). Objects are
created with a specialized member function called a
“constructor”.
 An instance of a class is destroyed (recycled) with a
specialized member function called a “destructor”
Circle
constructor(s): Circle(int,int),
Circle(float,int,int);
float computeArea();
float getRadius();
void setRadius(float);
// etc.
Type
name
Public
interface
 An ADT is a contract between
 The interface designer and ...
 The coder of a class that implements the
interface
 Precondition: any assumption/constraint on the
method data before the method begins
execution
 Postcondition: describes result of executing the
method
 A C++ program is a collection of functions and
classes.
 A class represents a set of objects that have
common properties.
 A class is a template for creating objects.
 A class represents a type.
 Type determines the set of values an object may
have.
 Type determines the operations that can be
performed on those values.
 In C++ there are two kinds of types:
 Primitive or build-in types
 User Defined or class types
 A class consists of members
 Data members – also called data fields or
attributes
 Member functions – also called operators,
functions or methods
 Data members are also sometimes called
instance variables because each object
(instance of a class) contains them.
 Data members may be either primitive or class
types.
private instance variables:
private float radius;
private Point center;
public methods:
constructor(s)
accessor methods (get)
mutator methods (set)
float computeArea()
… etc.
Represent a 2D “point”
Data: (x , y) coordinates, integer values
Methods:
create a point with coordinates (0,0)
create a point with coordinates (x,y),
get the x coordinate of a point,
get the y coordinate of a point,
draw a point
erase a point
move a point
etc.
 Unified Modeling Language (UML) is a standard
diagram notation for describing a class
Instance
of Person
Field
values
Class
name
Field
signatures:
type and name
Method signatures:
name, argument
types, result type
Point
constructor(s): Point(int,int),
Point(); // default (0,0)
int getX();
int getY();
// etc.
Type
name
Public
interface
private instance variables:
private int xCoordinate
private int yCoordinate
public methods:
constructor(s)
accessor methods (get)
mutator methods (set)
… etc.
 Class members that are declared in the public
section of a class definition are accessible to all
functions (inside or outside) the class.
 Class members that are declared in the private
section of a class definition are accessible only to
functions that are members of the class.
 Generally we want the operators (member
functions) visible to the users of the class.
 Thus they are declared public.
 Generally we want to keep the implementation
details (data members) hidden from the users of
the class
 Thus they are declared private.
 A constructor is a member function that initializes
the data members of an object when the object is
created.
 Note the use of
initialization lists
(more efficient than
assignment
statements)
class Point {
public:
Point(int i, int j) :
x(i), y(j) { }
Point() :
x(0), y(0) { }
private:
int x;
int y;
}
 A modifier function provides the ability to
modify the value of a private data member
void setX(int newX) {
x = newX;
}
 An accessor function provides the ability to
read the value of a private data member,
without changing it (note use of “const”)
int getX() const {
return x;
}
class Point {
public:
Point(int i, int j) :
x(i), y(j) { }
Point() :
x(0), y(0) { }
int getX() const
{ return x; }
private:
int x;
int y;
}
Client programmer can write:
Point p1(10,30);
Point p2;
int i = p1.getX();
messagereceiver
(this)
call the method
Point::getX()
class of the
receiver
no args
 A member function definition (implementation)
may be included in the class definition.
 The compiler can insert the code for the
function body where the function is called.
 This is known as an inline function.
 Use of inline member function is recommended
only for the following:
 Functions whose body is very small (one or two
lines)
● Constructors
● Accessors
● Modifiers
How would you compare two points, p1 and p2.
 Define a method to compare their x and y
coordinates.p
 p1.lessThan(p2)
 Overload the operator <
 p1 < p2
bool Point::operator< (const Point& other) const {
return (x < other.x)
|| ((x == other.x) && (y < other.y));
}
class Point {
public:
Point(int i, int j) :
x(i), y(j) { }
Point() :
x(0), y(0) { }
int getX() const
{ return x; }
bool operator<(const Point& other) const;
private:
int x;
int y;
}
bool Point::operator<
(const Point& other) const { return // you fill in...
}
Client programmer can write:
Point p1;
cin>>i; cin>>j;
Point p2(i,j);
if (p2 < p1) then cout << “lol”;
class Point {
public:
// other methods as before
std::ostream& operator<<(
std::ostream& os,
const Point& p);
private: // as before
}
ostream& operator<<(
ostream& os,
const Point& p) {
os << //... you fill in
return os;
}
Point p1(10,30);
cout << p1;
messagereceiver
(this)
problem:
The receiver is type ostream
arg
solution:
Make this function a “friend”
class Point {
public:
// other methods as before
friend std::ostream&
operator<<(
std::ostream& os,
const Point& p);
private: // as before
}
ostream& operator<<(
ostream& os,
const Point& p) {
os << //... you fill in
return os;
}
Point p1 =
new Point(10,30);
cout << p1;
solution:
Make this function a “friend”
Gives permission for this
function to have complete
access to the data members,
even though they are private
to the class
 A friend is an external function or class that is
given the same access to the members of a
class as if it were a member.
 We declare the ostream insertion operator to
be a friend
 So it can access the data members and insert
their string representation into the output
stream.
 Because this operator’s left-hand operand is an
ostream object, thus it cannot be defined as a
member of the Point class.
class Point {
public:
// other methods as before
friend std::ostream&
operator<<(
std::ostream& os,
const Point& p);
private: // as before
}
ostream& operator<<(
ostream& os,
const Point& p) {
os << //... you fill in
return os;
}
/* how do these differ? */
Point p1 = new Point(10,30);
Point p2(10,30);
/* how do these differ? */
cout << p1.getX() << endl;
cout << p1;
/* additional examples were
done in class */
class Point {
public:
// other methods as before
bool operator==(const
Point& other) const;
private: // as before
}
bool Point::operator==
(const Point& other) const
{ return // you fill in...
}
Point p3 =
new Point(10,30);
if (p2 == p3)
cout << “equal
points” << endl;
Now that we have implemented operators == and <,
what about <= ?
Reuse code!
1. Point.h header file (declarations & inline
code)
2. Point.cpp implementation file (code)
3. main.cpp test driver
g++ *.cpp
% g++ -c *.cpp
% g++ *.o –o testPt
testPt: main.o Point.o
g++ main.o Point.o –o testPt
main.o: main.cpp Point.h Point.o
g++ -c main.cpp –o main.o
Point.o: Point.h Point.cpp
g++ -c Point.cpp –o Point.o
clean:
rm –f *.o testPoint
Makefile
Could type this:
or
% make
% ./testPt
% make clean
 For Thursday, read Chapter 2, sections 2.6 – 2.9
of Maciel & Chapter 3, section 3.1
 Be prepared to write a simple class definition for
Circle
Quiz #1 next week, Thursday, 1/24, in class

More Related Content

What's hot

Dbms important questions and answers
Dbms important questions and answersDbms important questions and answers
Dbms important questions and answersLakshmiSarvani6
 
Data structures "1" (Lectures 2015-2016)
Data structures "1" (Lectures 2015-2016) Data structures "1" (Lectures 2015-2016)
Data structures "1" (Lectures 2015-2016) Ameer B. Alaasam
 
Introduction to database-Formal Query language and Relational calculus
Introduction to database-Formal Query language and Relational calculusIntroduction to database-Formal Query language and Relational calculus
Introduction to database-Formal Query language and Relational calculusAjit Nayak
 
Database Programming using SQL
Database Programming using SQLDatabase Programming using SQL
Database Programming using SQLAjit Nayak
 
Java Data Types
Java Data TypesJava Data Types
Java Data TypesSpotle.ai
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and OperatorsMarwa Ali Eissa
 
+2 Computer Science - Volume II Notes
+2 Computer Science - Volume II Notes+2 Computer Science - Volume II Notes
+2 Computer Science - Volume II NotesAndrew Raj
 
4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patilwidespreadpromotion
 
Revision notes for exam 2011 computer science with C++
Revision notes for exam 2011 computer science with C++Revision notes for exam 2011 computer science with C++
Revision notes for exam 2011 computer science with C++Deepak Singh
 
Structure & Union in C++
Structure & Union in C++Structure & Union in C++
Structure & Union in C++Davinder Kaur
 
oop lecture 3
oop lecture 3oop lecture 3
oop lecture 3Atif Khan
 
Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Raj Naik
 
Presentation on c structures
Presentation on c   structures Presentation on c   structures
Presentation on c structures topu93
 
1. Fundamental Concept - Data Structures using C++ by Varsha Patil
1. Fundamental Concept - Data Structures using C++ by Varsha Patil1. Fundamental Concept - Data Structures using C++ by Varsha Patil
1. Fundamental Concept - Data Structures using C++ by Varsha Patilwidespreadpromotion
 

What's hot (19)

Dbms important questions and answers
Dbms important questions and answersDbms important questions and answers
Dbms important questions and answers
 
Data structures "1" (Lectures 2015-2016)
Data structures "1" (Lectures 2015-2016) Data structures "1" (Lectures 2015-2016)
Data structures "1" (Lectures 2015-2016)
 
Introduction to database-Formal Query language and Relational calculus
Introduction to database-Formal Query language and Relational calculusIntroduction to database-Formal Query language and Relational calculus
Introduction to database-Formal Query language and Relational calculus
 
Database Programming using SQL
Database Programming using SQLDatabase Programming using SQL
Database Programming using SQL
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
 
Lesson 2.2 abstraction
Lesson 2.2   abstractionLesson 2.2   abstraction
Lesson 2.2 abstraction
 
+2 Computer Science - Volume II Notes
+2 Computer Science - Volume II Notes+2 Computer Science - Volume II Notes
+2 Computer Science - Volume II Notes
 
4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil
 
03. oop concepts
03. oop concepts03. oop concepts
03. oop concepts
 
Revision notes for exam 2011 computer science with C++
Revision notes for exam 2011 computer science with C++Revision notes for exam 2011 computer science with C++
Revision notes for exam 2011 computer science with C++
 
Structure & Union in C++
Structure & Union in C++Structure & Union in C++
Structure & Union in C++
 
Unit4
Unit4Unit4
Unit4
 
oop lecture 3
oop lecture 3oop lecture 3
oop lecture 3
 
Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive
 
SQL
SQL SQL
SQL
 
Presentation on c structures
Presentation on c   structures Presentation on c   structures
Presentation on c structures
 
1. Fundamental Concept - Data Structures using C++ by Varsha Patil
1. Fundamental Concept - Data Structures using C++ by Varsha Patil1. Fundamental Concept - Data Structures using C++ by Varsha Patil
1. Fundamental Concept - Data Structures using C++ by Varsha Patil
 
C++ language
C++ languageC++ language
C++ language
 

Viewers also liked

กฎหมายที่ใช้ในชีวิตประจำวัน ครั้งที่ 3
กฎหมายที่ใช้ในชีวิตประจำวัน ครั้งที่ 3กฎหมายที่ใช้ในชีวิตประจำวัน ครั้งที่ 3
กฎหมายที่ใช้ในชีวิตประจำวัน ครั้งที่ 3AJ Por
 
Arcadia Corporate Profile - New
Arcadia Corporate Profile - NewArcadia Corporate Profile - New
Arcadia Corporate Profile - NewIda Mazzola
 
อุปกรณ์เครือข่ายคอมพิวเตอร์6.3.29
อุปกรณ์เครือข่ายคอมพิวเตอร์6.3.29อุปกรณ์เครือข่ายคอมพิวเตอร์6.3.29
อุปกรณ์เครือข่ายคอมพิวเตอร์6.3.29choyoungjy_97
 
A story of love
A story of loveA story of love
A story of loveIvanet598
 
Cod train trainer
Cod train trainerCod train trainer
Cod train trainerdemaarif
 
Brabant Biennial Magazine 2012
Brabant Biennial Magazine 2012Brabant Biennial Magazine 2012
Brabant Biennial Magazine 2012Brabant Academy
 
Cripto-Stato Veneto: libertà e tecnologia, le due componenti fondamentali nel...
Cripto-Stato Veneto: libertà e tecnologia, le due componenti fondamentali nel...Cripto-Stato Veneto: libertà e tecnologia, le due componenti fondamentali nel...
Cripto-Stato Veneto: libertà e tecnologia, le due componenti fondamentali nel...Plebiscito Eu
 
Using Capability Development Centres To Assist Organisations In Achieving The...
Using Capability Development Centres To Assist Organisations In Achieving The...Using Capability Development Centres To Assist Organisations In Achieving The...
Using Capability Development Centres To Assist Organisations In Achieving The...Ramsey Hall Limited
 
ControllersLounge Boeblingen 18.02.2014
ControllersLounge Boeblingen 18.02.2014ControllersLounge Boeblingen 18.02.2014
ControllersLounge Boeblingen 18.02.2014Patrick Theobald
 
Convention 2015 Plebiscito.eu
Convention 2015 Plebiscito.euConvention 2015 Plebiscito.eu
Convention 2015 Plebiscito.euPlebiscito Eu
 
5.sinkronisasi proses
5.sinkronisasi proses5.sinkronisasi proses
5.sinkronisasi prosesAditya Asmara
 
Dal Referendum di indipendenza del Veneto del 2014 al Cripto-Stato Veneto ind...
Dal Referendum di indipendenza del Veneto del 2014 al Cripto-Stato Veneto ind...Dal Referendum di indipendenza del Veneto del 2014 al Cripto-Stato Veneto ind...
Dal Referendum di indipendenza del Veneto del 2014 al Cripto-Stato Veneto ind...Plebiscito Eu
 
Lassus title sequence pitch
Lassus   title sequence pitchLassus   title sequence pitch
Lassus title sequence pitchamber1236
 
Perspectieven en denkrichtingen voor bieb 2.0
Perspectieven en denkrichtingen voor bieb 2.0Perspectieven en denkrichtingen voor bieb 2.0
Perspectieven en denkrichtingen voor bieb 2.0Brabant Academy
 
Sepeda antik yogyakarta
Sepeda antik yogyakartaSepeda antik yogyakarta
Sepeda antik yogyakartademaarif
 

Viewers also liked (20)

List 2
List 2List 2
List 2
 
กฎหมายที่ใช้ในชีวิตประจำวัน ครั้งที่ 3
กฎหมายที่ใช้ในชีวิตประจำวัน ครั้งที่ 3กฎหมายที่ใช้ในชีวิตประจำวัน ครั้งที่ 3
กฎหมายที่ใช้ในชีวิตประจำวัน ครั้งที่ 3
 
Arcadia Corporate Profile - New
Arcadia Corporate Profile - NewArcadia Corporate Profile - New
Arcadia Corporate Profile - New
 
อุปกรณ์เครือข่ายคอมพิวเตอร์6.3.29
อุปกรณ์เครือข่ายคอมพิวเตอร์6.3.29อุปกรณ์เครือข่ายคอมพิวเตอร์6.3.29
อุปกรณ์เครือข่ายคอมพิวเตอร์6.3.29
 
cos-app
cos-appcos-app
cos-app
 
A story of love
A story of loveA story of love
A story of love
 
Ippbx
IppbxIppbx
Ippbx
 
Cod train trainer
Cod train trainerCod train trainer
Cod train trainer
 
Brabant Biennial Magazine 2012
Brabant Biennial Magazine 2012Brabant Biennial Magazine 2012
Brabant Biennial Magazine 2012
 
Cripto-Stato Veneto: libertà e tecnologia, le due componenti fondamentali nel...
Cripto-Stato Veneto: libertà e tecnologia, le due componenti fondamentali nel...Cripto-Stato Veneto: libertà e tecnologia, le due componenti fondamentali nel...
Cripto-Stato Veneto: libertà e tecnologia, le due componenti fondamentali nel...
 
Hero
HeroHero
Hero
 
Using Capability Development Centres To Assist Organisations In Achieving The...
Using Capability Development Centres To Assist Organisations In Achieving The...Using Capability Development Centres To Assist Organisations In Achieving The...
Using Capability Development Centres To Assist Organisations In Achieving The...
 
ControllersLounge Boeblingen 18.02.2014
ControllersLounge Boeblingen 18.02.2014ControllersLounge Boeblingen 18.02.2014
ControllersLounge Boeblingen 18.02.2014
 
Convention 2015 Plebiscito.eu
Convention 2015 Plebiscito.euConvention 2015 Plebiscito.eu
Convention 2015 Plebiscito.eu
 
5.sinkronisasi proses
5.sinkronisasi proses5.sinkronisasi proses
5.sinkronisasi proses
 
Dal Referendum di indipendenza del Veneto del 2014 al Cripto-Stato Veneto ind...
Dal Referendum di indipendenza del Veneto del 2014 al Cripto-Stato Veneto ind...Dal Referendum di indipendenza del Veneto del 2014 al Cripto-Stato Veneto ind...
Dal Referendum di indipendenza del Veneto del 2014 al Cripto-Stato Veneto ind...
 
Chosita 29.pdf
Chosita 29.pdfChosita 29.pdf
Chosita 29.pdf
 
Lassus title sequence pitch
Lassus   title sequence pitchLassus   title sequence pitch
Lassus title sequence pitch
 
Perspectieven en denkrichtingen voor bieb 2.0
Perspectieven en denkrichtingen voor bieb 2.0Perspectieven en denkrichtingen voor bieb 2.0
Perspectieven en denkrichtingen voor bieb 2.0
 
Sepeda antik yogyakarta
Sepeda antik yogyakartaSepeda antik yogyakarta
Sepeda antik yogyakarta
 

Similar to 02.adt (20)

Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Lecture5
Lecture5Lecture5
Lecture5
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
Op ps
Op psOp ps
Op ps
 
Overloading
OverloadingOverloading
Overloading
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer Melayi
 
DS Unit 6.ppt
DS Unit 6.pptDS Unit 6.ppt
DS Unit 6.ppt
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
 
OOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxOOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptx
 
Oops concept
Oops conceptOops concept
Oops concept
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
L10
L10L10
L10
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
 

Recently uploaded

chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 

Recently uploaded (20)

★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 

02.adt

  • 1. Abstract Data Types (ADT) and C++ Classes 1-15-2013
  • 2.  Abstract Data Types (ADT) & UML  C++ Class definition & implementation  constructors, accessors & modifiers  overloading operators  friend functions HW#1 posted – due: Tuesday, 1/22 Quiz Thursday, 1/24
  • 3.  FAQ 5.14 What is an abstraction and why is it important?  FAQ 5.15 Should abstractions be user-centric or developer-centric? An abstraction is a simplified vew of an object in the user’s own vocabulary. In OO and C++, an abstraction is the simplest interface to an object that provides all the features and services the intended users expect. User-centric. Focus on the user’s point of view.
  • 4.  Computes what each employee should be paid for a day of work. Reads a file containing start and stop times for each employee. Then calculates and saves the pay amounts to another file. int runPayCalculator (const char csInputFileName[], const char csOutputFileName[]) Sample input: 510 + 24601 990 - 24601 Sample output 24601 96
  • 5. int runPayCalculator (const char csInputFileName[], const char csOutputFileName[]) Algorithm: call computeHours and then computeAndWritePay Data structure: The number of hours worked by each employee is stored in an array indexed by the possible employee numbers. This array is of size MAX_EMPLOYEE_NUMBER + 1, where MAX_EMPLOYEE_NUMBER is a global constant
  • 6. In a well-designed modular program, software components should satisfy the following two properties: 1. Each component performs one well-defined task. (i.e. “cohesion”) 2. Each component is as independent as possible from the others. (i.e. loosely coupled”)
  • 7. 1. Easier to understand; little redundant code. 2. Facilitates software reuse. 3. Easier to implement. 4. Easier to test. 5. Easier to modify.
  • 8.  Independence of modules is typically achieved by “information hiding” (which can be achieved by “encapsulation”).  Procedural Abstraction  Use of a function depends on its purpose (what it does) but not on its implementation (how it does it).  FAQ 5.18 What’s the value of separating interface from implementation? It’s a key to eliminating the ripple effect when a change is made.
  • 9.  Class designer/implementer - designs & implements a class vs.  Client programmer - uses a class for an application vs.  End-user - uses the application
  • 10.  Procedural Abstraction (Algorithm)  Data Abstraction (Data)
  • 11.  An Abstract Data Type (ADT) is a specification of a set of data and a set of operations that can be performed on the data. examples: String Circle List Dice Dictionary Song Student Telephone Directory Time Complex number
  • 12.  In C++, a class represents an ADT.  An “instance” of a class is a specific object which is created, and the data members are filled in with values (possibly default values). Objects are created with a specialized member function called a “constructor”.  An instance of a class is destroyed (recycled) with a specialized member function called a “destructor”
  • 13. Circle constructor(s): Circle(int,int), Circle(float,int,int); float computeArea(); float getRadius(); void setRadius(float); // etc. Type name Public interface
  • 14.  An ADT is a contract between  The interface designer and ...  The coder of a class that implements the interface  Precondition: any assumption/constraint on the method data before the method begins execution  Postcondition: describes result of executing the method
  • 15.  A C++ program is a collection of functions and classes.  A class represents a set of objects that have common properties.  A class is a template for creating objects.  A class represents a type.  Type determines the set of values an object may have.  Type determines the operations that can be performed on those values.  In C++ there are two kinds of types:  Primitive or build-in types  User Defined or class types
  • 16.  A class consists of members  Data members – also called data fields or attributes  Member functions – also called operators, functions or methods  Data members are also sometimes called instance variables because each object (instance of a class) contains them.  Data members may be either primitive or class types.
  • 17. private instance variables: private float radius; private Point center; public methods: constructor(s) accessor methods (get) mutator methods (set) float computeArea() … etc.
  • 18. Represent a 2D “point” Data: (x , y) coordinates, integer values Methods: create a point with coordinates (0,0) create a point with coordinates (x,y), get the x coordinate of a point, get the y coordinate of a point, draw a point erase a point move a point etc.
  • 19.  Unified Modeling Language (UML) is a standard diagram notation for describing a class Instance of Person Field values Class name Field signatures: type and name Method signatures: name, argument types, result type
  • 20. Point constructor(s): Point(int,int), Point(); // default (0,0) int getX(); int getY(); // etc. Type name Public interface
  • 21. private instance variables: private int xCoordinate private int yCoordinate public methods: constructor(s) accessor methods (get) mutator methods (set) … etc.
  • 22.  Class members that are declared in the public section of a class definition are accessible to all functions (inside or outside) the class.  Class members that are declared in the private section of a class definition are accessible only to functions that are members of the class.  Generally we want the operators (member functions) visible to the users of the class.  Thus they are declared public.  Generally we want to keep the implementation details (data members) hidden from the users of the class  Thus they are declared private.
  • 23.  A constructor is a member function that initializes the data members of an object when the object is created.  Note the use of initialization lists (more efficient than assignment statements) class Point { public: Point(int i, int j) : x(i), y(j) { } Point() : x(0), y(0) { } private: int x; int y; }
  • 24.  A modifier function provides the ability to modify the value of a private data member void setX(int newX) { x = newX; }  An accessor function provides the ability to read the value of a private data member, without changing it (note use of “const”) int getX() const { return x; }
  • 25. class Point { public: Point(int i, int j) : x(i), y(j) { } Point() : x(0), y(0) { } int getX() const { return x; } private: int x; int y; } Client programmer can write: Point p1(10,30); Point p2; int i = p1.getX(); messagereceiver (this) call the method Point::getX() class of the receiver no args
  • 26.  A member function definition (implementation) may be included in the class definition.  The compiler can insert the code for the function body where the function is called.  This is known as an inline function.  Use of inline member function is recommended only for the following:  Functions whose body is very small (one or two lines) ● Constructors ● Accessors ● Modifiers
  • 27. How would you compare two points, p1 and p2.  Define a method to compare their x and y coordinates.p  p1.lessThan(p2)  Overload the operator <  p1 < p2 bool Point::operator< (const Point& other) const { return (x < other.x) || ((x == other.x) && (y < other.y)); }
  • 28. class Point { public: Point(int i, int j) : x(i), y(j) { } Point() : x(0), y(0) { } int getX() const { return x; } bool operator<(const Point& other) const; private: int x; int y; } bool Point::operator< (const Point& other) const { return // you fill in... } Client programmer can write: Point p1; cin>>i; cin>>j; Point p2(i,j); if (p2 < p1) then cout << “lol”;
  • 29. class Point { public: // other methods as before std::ostream& operator<<( std::ostream& os, const Point& p); private: // as before } ostream& operator<<( ostream& os, const Point& p) { os << //... you fill in return os; } Point p1(10,30); cout << p1; messagereceiver (this) problem: The receiver is type ostream arg solution: Make this function a “friend”
  • 30. class Point { public: // other methods as before friend std::ostream& operator<<( std::ostream& os, const Point& p); private: // as before } ostream& operator<<( ostream& os, const Point& p) { os << //... you fill in return os; } Point p1 = new Point(10,30); cout << p1; solution: Make this function a “friend” Gives permission for this function to have complete access to the data members, even though they are private to the class
  • 31.  A friend is an external function or class that is given the same access to the members of a class as if it were a member.  We declare the ostream insertion operator to be a friend  So it can access the data members and insert their string representation into the output stream.  Because this operator’s left-hand operand is an ostream object, thus it cannot be defined as a member of the Point class.
  • 32. class Point { public: // other methods as before friend std::ostream& operator<<( std::ostream& os, const Point& p); private: // as before } ostream& operator<<( ostream& os, const Point& p) { os << //... you fill in return os; } /* how do these differ? */ Point p1 = new Point(10,30); Point p2(10,30); /* how do these differ? */ cout << p1.getX() << endl; cout << p1; /* additional examples were done in class */
  • 33. class Point { public: // other methods as before bool operator==(const Point& other) const; private: // as before } bool Point::operator== (const Point& other) const { return // you fill in... } Point p3 = new Point(10,30); if (p2 == p3) cout << “equal points” << endl; Now that we have implemented operators == and <, what about <= ? Reuse code!
  • 34. 1. Point.h header file (declarations & inline code) 2. Point.cpp implementation file (code) 3. main.cpp test driver g++ *.cpp
  • 35. % g++ -c *.cpp % g++ *.o –o testPt testPt: main.o Point.o g++ main.o Point.o –o testPt main.o: main.cpp Point.h Point.o g++ -c main.cpp –o main.o Point.o: Point.h Point.cpp g++ -c Point.cpp –o Point.o clean: rm –f *.o testPoint Makefile Could type this: or % make % ./testPt % make clean
  • 36.  For Thursday, read Chapter 2, sections 2.6 – 2.9 of Maciel & Chapter 3, section 3.1  Be prepared to write a simple class definition for Circle Quiz #1 next week, Thursday, 1/24, in class