Abstract Data Type and C++ Classes 1. Object-oriented Programming 2. Abstract Data Types 3. Classes...

Post on 04-Jan-2016

232 views 2 download

transcript

Abstract Data Type and C++ Classes

1.1. Object-oriented ProgrammingObject-oriented Programming

2.2. Abstract Data TypesAbstract Data Types

3.3. Classes and ObjectsClasses and Objects

4.4. ExamplesExamples

5.5. Member Functions and Member VariablesMember Functions and Member Variables

6.6. ConstructorsConstructors

7.7. Operator OverloadingOperator Overloading

Object-Oriented Programming (OOP)

Procedure-oriented ProgrammingProcedure-oriented Programmingo Traditional method uses command statementsTraditional method uses command statementso Imperative methodImperative method

Object-oriented ProgrammingObject-oriented Programmingo Views program as set of objects interacting Views program as set of objects interacting

with each otherwith each othero Class—template for creating objectsClass—template for creating objectso Class encapsulates data and behaviorClass encapsulates data and behavior

Abstract Data Type (ADT)

ADT—A way of defining a complex data type ADT—A way of defining a complex data type by specifying operations (without specifying by specifying operations (without specifying details)details)

Example 1—ADT ListExample 1—ADT Listo Create a listCreate a listo Insert an item into the listInsert an item into the listo Remove an item from the listRemove an item from the listo Check if the list is emptyCheck if the list is emptyo Display list contentsDisplay list contents

Abstract Data Type (ADT)

Example 2—ADT FractionExample 2—ADT Fractiono Create a fractionCreate a fractiono Add another fraction and return the sumAdd another fraction and return the sumo Subtract another fraction and return the differenceSubtract another fraction and return the differenceo Return the numerator of the fractionReturn the numerator of the fractiono Display the fractionDisplay the fraction

Classes and Objects

ClassClasso Implements ADT’s in a programming language Implements ADT’s in a programming language

(C++)(C++)o Specifies actions (behavior) Specifies actions (behavior) o Encapsulates the data which describes an object Encapsulates the data which describes an object

(attributes)(attributes)o Is a template for creating (instantiating) objects Is a template for creating (instantiating) objects

of the classof the class

Example--Circle

CircleCircleo What operations (behavior) are appropriate for What operations (behavior) are appropriate for

a circle?a circle?o Create a circle with a particular radiusCreate a circle with a particular radiuso Calculate its circumferenceCalculate its circumferenceo Calculate its areaCalculate its area

Class Circle (class interface)

class Circle {public: Circle(double r); double getRadius(); double circumference(); double area();private: double radius;};

Save as circle.h

Class Circle (class implementation)#include "circle.h"

Circle::Circle(double r){ radius = r;}

double Circle::getRadius(){ return radius;}

double Circle::circumference(){ return 2 * 3.14159 * radius;}

double Circle::area(){ return 2 * 3.14159 * radius;}

Save as circle.cpp

Class Circle (used in client program)#include <iostream>#include "circle2.h"using namespace std;

int main(){ double r1 = 1.0; double r2 = 3.0; Circle c1(r1); Circle2 c2(r2); cout << "Circle with radius " << r1 << " has area of " << c1.area() << endl; cout << "Circle with radius " << r2 << " has volume of " << c2.volume() << endl;

return 0;}

Save as circleTest.cpp

Your Turn

1.1. In the main(), instantiate a third circle In the main(), instantiate a third circle whose radius is the same as that of c2.whose radius is the same as that of c2.

2.2. Print the area and the volume of the third Print the area and the volume of the third circle.circle.

Example--Fraction

FractionFractiono What operations (behavior) are appropriate for What operations (behavior) are appropriate for

a fraction?a fraction?o Create a fractionCreate a fractiono Add another fraction and return the sumAdd another fraction and return the sumo Subtract another fraction and reutrn the differenceSubtract another fraction and reutrn the differenceo Display the fractionDisplay the fraction

Class Fraction (class interface)

class Fraction{public: Fraction(int n, int d); Fraction add(Fraction f); Fraction subtract(Fraction f); void display();private: int numer; int denom;};

Save as fraction.h

Class Fraction (class implementation)#include <iostream>#include "fraction"using namespace std;

Fraction:: Fraction(int n, int d){ numer = h; denom = d;}

Fraction Fraction ::add(Fraction f){ . . . }. . .Void Fraction::display(){ . . .}

Save as fraction.cpp

Class Fraction(used in client program)#include <iostream>#include "fraction.h"using namespace std;

int main(){ Fraction f1(3, 4); Fraction f2(1, 2); f1.display(); cout << endl; f2.display(); cout << endl;

Fraction sum = f1.add(f2); Fraction diff = f1.subtract(f2); cout << "Sum  "; sum.display(); cout << endl; cout << "Diff: "; diff.display(); cout << endl;

return 0;} Save as fractionTest.cpp

Class List (used in client program)#include <iostream>#include "fraction.h"using namespace std;

int main(){ Fraction f1(3, 4); Fraction f2(1, 2); f1.display(); cout << endl; f2.display(); cout << endl;

Fraction sum = f1.add(f2); Fraction diff = f1.subtract(f2); cout << "Sum  "; sum.display(); cout << endl; cout << "Diff: "; diff.display(); cout << endl;

return 0;} Save as listTest.cpp

Example--List

ListListo What operations (behavior) are appropriate for What operations (behavior) are appropriate for

a list?a list?o Create a listCreate a listo Insert an item at the list endInsert an item at the list endo Check if the list is emptyCheck if the list is emptyo Display list contentsDisplay list contents

Class List(class interface)

#define MAX_SIZE 100;

class List{public: List(); void append(int item); void removeAt(int pos); bool isEmpty(); void print();private: int data[MAX_SIZE]; int count;}; Save as list.h

Class List (class implementation)#include <iostream>#include "list.h"using namespace std;

List::List(){ count = 0;}

void List::append(int item){ . . . }

. . .

void List::print(){ . . .}

Save as list.cpp

Class List (used in client program)#include <iostream>#include "list.h"using namespace std;

int main(){ int mylist[] = {2, 4, 6, 8, 10}; int listCount = 5; List list;

for (int i = 0; i < listCount; i++){ list.append(mylist[i]); }

cout << "Original List\n"; list.print(); cout << endl; . . .} Save as listTest.cpp

What is this Object ?

The plan is to describe a The plan is to describe a thinking cap by telling thinking cap by telling you what actions can be you what actions can be done to it.done to it.

Using the Object’s Slots

You may put a piece of You may put a piece of paper in each of the two paper in each of the two slots (green and red), with a slots (green and red), with a sentence written on each.sentence written on each.

You may push the green You may push the green button and the thinking cap button and the thinking cap will speak the sentence will speak the sentence from the green slot’s paper.from the green slot’s paper.

And same for the red And same for the red button.button.

Example

Example

That test was a breeze !

Example

I shouldstudy harder !

Thinking Cap Implementation

We can implement the We can implement the thinking cap using a thinking cap using a data type called a data type called a classclass..

class thinking_cap {

. . .

};

Thinking Cap Implementation

The class will have The class will have two components called two components called green_stringgreen_string and and red_stringred_string. These . These compnents are strings compnents are strings which hold the which hold the information that is information that is placed in the two slots.placed in the two slots.

Using a class permits Using a class permits two new features . . .two new features . . .

class thinking_cap { . . . char green_string[50]; char red_string[50]; };

Thinking Cap Implementation

The two components The two components will be will be private private member variablesmember variables. . This ensures that This ensures that nobody can directly nobody can directly access this access this information. The information. The only access is through only access is through functions that we functions that we provide for the class.provide for the class.

class thinking_cap { . . .private: char green_string[50]; char red_string[50];};

Thinking Cap Implementation

In a class, the In a class, the functions which functions which manipulate the class manipulate the class are also listed.are also listed.

class thinking_cap {public: . . .private: char green_string[50]; char red_string[50];};Prototypes for the

thinking cap member functions go here

Thinking Cap Implementation

class thinking_cap {public: void slots(char new_green[ ], char new_red[ ]); void push_green( ) const; void push_red( ) const;private: char green_string[50]; char red_string[50];};

Our thinking cap has at least three member functions:

Function

bod

ies

will b

e else

where.

Thinking Cap Implementation

class thinking_cap {public: void slots(char new_green[ ], char new_red[ ]); void push_green( ) const; void push_red( ) const;private: char green_string[50]; char red_string[50];};

The keyword const appears after two prototypes:

This means that thesefunctions will not changethe data stored in athinking_cap.

Files for the Thinking Cap

The thinking_cap class The thinking_cap class definition, which we have definition, which we have just seen, is placed with just seen, is placed with documentation in a file called documentation in a file called thinker.hthinker.h, outlined here., outlined here.

The implementations of the The implementations of the three three member functions will be member functions will be placed in a separate file placed in a separate file called called thinker.cxxthinker.cxx, which we , which we will examine in a few will examine in a few minutes.minutes.

Documentation

Class definition:• thinking_cap class definition which we have already seen

Using the Thinking Cap

A program that A program that wants to use the wants to use the thinking cap thinking cap must must includeinclude the the thinker header thinker header file (along with file (along with its other header its other header inclusions).inclusions).

#include <iostream.h>#include <stdlib.h>#include "thinker.h"

...

Using the Thinking Cap

Just for fun, the Just for fun, the example program example program will declare two will declare two thinking_cap thinking_cap objectsobjects named named student and fan.student and fan.

#include <iostream.h>#include <stdlib.h>#include "thinker.h"

int main( ) { thinking_cap student; thinking_cap fan;

Using the Thinking Cap

The program The program starts by starts by calling the calling the slots member slots member function for function for student.student.

#include <iostream.h>#include <stdlib.h>#include "thinker.h"

int main( ) { thinking_cap student; thinking_cap fan;

student.slots( "Hello", "Goodbye");

Using the Thinking Cap

The member The member function function activation activation consists of four consists of four parts, starting parts, starting with the object with the object name.name.

int main( ) { thinking_cap student; thinking_cap fan;

student.slots( "Hello", "Goodbye");

Name of the object

Using the Thinking Cap

The instance The instance name is followed name is followed by a period.by a period. int main( )

{ thinking_cap student; thinking_cap fan;

student.slots( "Hello", "Goodbye");A

Per

iod

Using the Thinking Cap

After the period After the period is the name of is the name of the member the member function that you function that you are activating.are activating.

int main( ) { thinking_cap student; thinking_cap fan;

student.slots( "Hello", "Goodbye");

Name of the

Function

Using the Thinking Cap

Finally, the Finally, the arguments for arguments for the member the member function. In this function. In this example the first example the first argument argument (new_green) is (new_green) is "Hello" and the "Hello" and the second argument second argument (new_red) is (new_red) is "Goodbye"."Goodbye".

#include "thinker.h"

int main( ) { thinking_cap student; thinking_cap fan;

student.slots( "Hello", "Goodbye");

Arg

umen

ts

A Quiz

How would you How would you activate student's activate student's push_green push_green member function ?member function ?

What would be the What would be the output of student's output of student's push_green push_green member function member function at this point in the at this point in the program ?program ?

int main( ) { thinking_cap student; thinking_cap fan;

student.slots( "Hello", "Goodbye");

A Quiz

Notice that the Notice that the push_green push_green member member function has no function has no arguments.arguments.

At this point, At this point, activating activating student.push_green student.push_green

will print the stringwill print the string

HelloHello..

int main( ) { thinking_cap student; thinking_cap fan;

student.slots( "Hello", "Goodbye");

student.push_green( );

A Quiz

Trace through this Trace through this program, and tell program, and tell me the complete me the complete output.output.

int main( ) { thinking_cap student; thinking_cap fan;

student.slots( "Hello", "Goodbye");

fan.slots( "Go Cougars!", "Boo!");

student.push_green( );

fan.push_green( );

student.push_red( ); . . .

A Quiz

HelloHello

Go Cougars!Go Cougars!

GoodbyeGoodbyeint main( ) { thinking_cap student; thinking_cap fan;

student.slots( "Hello", "Goodbye");

fan.slots( "Go Cougars!", "Boo!");

student.push_green( );

fan.push_green( );

student.push_red( ); . . .

What you know about Objects

Class = Data + Member Functions.Class = Data + Member Functions. You know how to define a new class type, and You know how to define a new class type, and

place the definition in a header file.place the definition in a header file. You know how to use the header file in a You know how to use the header file in a

program which declares instances of the class program which declares instances of the class type.type.

You know how to activate member functions.You know how to activate member functions. But you still need to learn how to write the But you still need to learn how to write the

bodies of a class’s member functions.bodies of a class’s member functions.

Thinking Cap Implementation

class thinking_cap{public: void slots(char new_green[ ], char new_red[ ]); void push_green( ); void push_red( );private: char green_string[50]; char red_string[50];};

Remember that the member function’s bodies Remember that the member function’s bodies generally appear in a separate .cxx file.generally appear in a separate .cxx file.

Function

bod

ies

will b

e in .c

xx fi

le.

Thinking Cap Implementation

class thinking_cap {public: void slots(char new_green[ ], char new_red[ ]); void push_green( ); void push_red( );private: char green_string[50]; char red_string[50];};

We will look at the body of slots, which must copy its We will look at the body of slots, which must copy its two arguments to the two private member variables.two arguments to the two private member variables.

Thinking Cap Implementation

void thinking_cap::slots(char new_green[ ], char new_red[ ]){ assert(strlen(new_green) < 50); assert(strlen(new_red) < 50); strcpy(green_string, new_green); strcpy(red_string, new_red);}

For the most part, the function’s body is no different For the most part, the function’s body is no different than any other function body.than any other function body.

But there are two special features about a But there are two special features about a member function’s body . . .member function’s body . . .

Thinking Cap Implementation

In the heading, the function's name is preceded by the In the heading, the function's name is preceded by the class name and :: - otherwise C++ won't realize this class name and :: - otherwise C++ won't realize this is a class’s member function.is a class’s member function.

void thinking_cap::slots(char new_green[ ], char new_red[ ]){ assert(strlen(new_green) < 50); assert(strlen(new_red) < 50); strcpy(green_string, new_green); strcpy(red_string, new_red);}

Thinking Cap Implementation

Within the body of the function, the class’s member Within the body of the function, the class’s member variables and other member functions may all be variables and other member functions may all be accessed.accessed.

void thinking_cap::slots(char new_green[ ], char new_red[ ]){ assert(strlen(new_green) < 50); assert(strlen(new_red) < 50); strcpy(green_string, new_green); strcpy(red_string, new_red);}

Thinking Cap Implementation

Within the body of the function, the class’s member Within the body of the function, the class’s member variables and other member functions may all be variables and other member functions may all be accessed.accessed.

void thinking_cap::slots(char new_green[ ], char new_red[ ]){ assert(strlen(new_green) < 50); assert(strlen(new_red) < 50); strcpy(green_string, new_green); strcpy(red_string, new_red);}

But, whose member variables are

these? Are they

student.green_string

student.red_string

fan.green_string

fan.red_string?

Thinking Cap Implementation

Within the body of the function, the class’s member Within the body of the function, the class’s member variables and other member functions may all be variables and other member functions may all be accessed.accessed.

void thinking_cap::slots(char new_green[ ], char new_red[ ]){ assert(strlen(new_green) < 50); assert(strlen(new_red) < 50); strcpy(green_string, new_green); strcpy(red_string, new_red);}

If we activate student.slots:

student.green_string

student.red_string

Thinking Cap Implementation

Within the body of the function, the class’s member Within the body of the function, the class’s member variables and other member functions may all be variables and other member functions may all be accessed.accessed.

void thinking_cap::slots(char new_green[ ], char new_red[ ]){ assert(strlen(new_green) < 50); assert(strlen(new_red) < 50); strcpy(green_string, new_green); strcpy(red_string, new_red);}

If we activate fan.slots:

fan.green_string

fan.red_string

Thinking Cap Implementation

void thinking_cap::push_green {

cout << green_string << endl;

}

Here is the implementation of the push_green Here is the implementation of the push_green member function, which prints the green message:member function, which prints the green message:

Thinking Cap Implementation

void thinking_cap::push_green {

cout << green_string << endl;

}

Here is the implementation of the push_green Here is the implementation of the push_green member function, which prints the green message:member function, which prints the green message:

Notice how this member function implementation uses the green_string member variable of the object.

A Common Pattern

Often, one or more member functions will Often, one or more member functions will place data in the member variables...place data in the member variables...

class thinking_cap {public: void slots(char new_green[ ], char new_red[ ]); void push_green( ) const; void push_red( ) const;private: char green_string[50]; char red_string[50];};

...so that other member functions may use that data.

slots push_green & push_red

Member Functions

class Circle {public: Circle(double r); double getRadius() const; double circumference() const; double area() const; void setRadius(double r);private: double radius;};

• Constructors• Circle(double r)

• Accesor Functions• getRadius()

• Calculator Functions• circumference()• area()

• Modifier Functions• setRadius(double r)

• Others

Member Variables

class Circle {public: Circle(double r); double getRadius() const; double circumference() const; double area() const; void setRadius(double r);private: double radius;};

• double radius

Constructors

Used to instantiate an object of a given classUsed to instantiate an object of a given classo E.g., in mainE.g., in main(): Circle c1;(): Circle c1; Circle c2(3.0); Circle c2(3.0);

Has the same name as the class nameHas the same name as the class nameo E.g., E.g., class Circle(class Circle( Circle(); Circle();

Has no return typeHas no return type Can be overloadedCan be overloaded

o E.g., E.g., Circle();Circle(); Circle(double r); Circle(double r);

Operator Overloading

int main(){ Fraction f1(3, 4); Fraction f2(1, 2); . . . Fraction sum = f1.add(f2); Fraction diff = f1.subtract(f2); . . .}

class Fraction{public: Fraction(int n, int d); Fraction add(Fraction f); . . .

Operator Overloading

int main(){ Fraction f1(3, 4); Fraction f2(1, 2); . . . Fraction sum = f1 + f2; Fraction diff = f1 – f2; . . .}

class Fraction{public: Fraction(int n, int d); Fraction +(Fraction f); . . .

It would be nice if we could use the operator symbol “+,” instead of “add”

Operator Overloading

class Fraction{public: . . . Fraction +(Fraction f); . . .

. . .Fraction Fraction::operator +(Fraction f){ Fraction s; s.numer = numer * f.denom + denom * f.numer; s.denom = denom * f.denom; return s;}

Using Overloaded Operator

class Fraction{public: . . . Fraction +(Fraction f); . . .

int main(){ Fraction f1(3, 4); Fraction f2(1, 2); . . . Fraction sum = f1 + f2; . . .}

Think of

Classes have member variables and member Classes have member variables and member functions. functions.

An object is a variable where the data type is a An object is a variable where the data type is a class.class.

Class is like a template (cookie cutter) for creating Class is like a template (cookie cutter) for creating objects of that class.objects of that class.

Creating an object of a class is described as Creating an object of a class is described as “instantiating” the class.“instantiating” the class.E.g., E.g., Thinking_cap mycap;Thinking_cap mycap;

Summary