8/12/10

TODAY

Project presentations

COMP 10 Object-oriented programming EXPLORING COMPUTER SCIENCE

Course evaluations Lecture 10 Object-oriented programming

PROCEDURAL PROGRAMMING PROCEDURAL PROGRAMMING

As programs get larger, What if some part of the global data it becomes increasingly difficult needs to be changed (to improve to maintain a large collection of performance or to add new functions capabilities)?

Often becomes necessary to use A large number of functions global variables may be affected

Defined outside of all functions All functions have access to them

OBJECTS TO THE RESCUE CUSTOM TYPES

Keep the data and the functions that work with them together A class is a template or blueprint for objects May contain variables and functions Primitive types and functions: Procedural programming Can use classes to create new types: Object-oriented programming An object is an instance of a particular class

1 8/12/10

OBJECTS TO THE RESCUE CLASS: Muppet

An object’s member variables: Variables: Functions:

Set of variables of certain types name speak() Store information or current state of the object species getSpecies() color getColor() An object’s member functions: numberOfLegs Let the main program or other objects modify the state series Allow information to be communicated between objects

Muppet OBJECTS CLASS: MuppetSeries

Variables: Functions:

name listCharacters()

seriesType addNewCharacter() castofCharacters

Variables: Variables: name = “Kermit” name = “Rowlf” species = “Frog” species = “Dog” color = “Green” color = “Brown” numberOfLegs = 2 numberOfLegs = 4 series = “Sesame Street” series = “Muppet Show”

MuppetSeries OBJECTS ENCAPSULATION

The data members are encapsulated: Hidden from other parts of Variables: Variables: the program and accessible only through member functions name = “Sesame Street” name = “Muppet Show” seriesType = “TV” seriesType = “TV” castofCharacters = castofCharacters = When we want to change the way that an object is implemented, only a small number of functions need to be changed

Those member functions are the interface to the object

2 8/12/10

DEFINING A CLASS BASIC CLASS FORMAT

Don’t implement a single object; implement a class class ClassName { A class describes a set of objects with the same behavior public: Any part of the program // public interface should be able to call the member functions To define a class, specify the behavior by providing private: implementations for the member functions and by defining the Only member functions of // private data members data members for the objects the class can access data };

Implement the member functions to specify the behavior Define the data members to hold the object’s data

Muppet USING Muppets IN main()

class Muppet class Muppet int main() { { { public: public: // Create an object. // public interface // public interface Muppet kermit; kermit.name = “Kermit The Frog”; private: private: kermit.species = “Frog”; // private data members // private data members kermit.color = “Green”; string name; string name; kermit.numberOfLegs = 2; string species; string species; kermit.series = “Sesame Street”; string color; string color; int numberOfLegs; int numberOfLegs; // Create another object. string series; string series; Muppet rowlf; }; }; ...

USING Muppets IN main() OBSERVATIONS

main() not declared in the Muppet class kermit name “Kermit The Frog” species “Frog” color “Green” Member variables numberofLegs 2 Declared in a class, outside of any method series “Sesame Street” Exist as long as the containing object exists Local variables

rowlf name Exist only during the execution of its containing method species color Dot (.) operations numberofLegs Access a member variable series Call a member function; the object is the implicit parameter

3 8/12/10

OBJECT-ORIENTED PROGRAMMING DESIGNING A CLASS: CASH REGISTER

Need member functions to An object encapsulates state and behavior • Clear the cash register to start a new sale State  Variables • Add the price of an item Behavior  Functions • Get the total amount owed and the count of items purchased

A class is a template or blueprint for objects An object is an instance of a particular class

Each object is responsible for carrying out a set of related tasks Objects “talk” to each other to complete tasks

DESIGNING A CLASS: CASH REGISTER MEMBER FUNCTIONS

Need member functions to There are two kinds of member functions: • Clear the cash register to start a new sale • Mutators • Add the price of an item • Accessors • Get the total amount owed and the count of items purchased

A mutator modifies the data members of the object The public interface supports these activities:

class CashRegister class CashRegister { { public: public: void clear(); void clear(); Clear the cash register void add_item(double price); void add_item(double price); to start a new sale double get_total() const; double get_total() const; int get_count() const; int get_count() const; private: private: // data members will go here // data members will go here }; };

MEMBER FUNCTIONS CALLING MEMBER FUNCTIONS

There are two kinds of member functions: First create a variable of type CashRegister • Mutators • Accessors CashRegister register1;

A mutator modifies the data members of the object Then use the dot class CashRegister { operator to call the public: member functions: void clear(); void add_item(double price); Add the price of an item double get_total() const; register1.clear(); int get_count() const; register1.add_item(1.95); private: // data members will go here };

4 8/12/10

MEMBER FUNCTIONS THE INTERFACE

There are two kinds of member functions:

• Mutators • Accessors

An accessor function queries a data member of the object

class CashRegister { public: Access member variables using the dot operator void clear(); void add_item(double price); double get_total() const; Get the total amount This statement will print the current total: int get_count() const; owed and the count cout << register1.get_total() << endl ; private: of items purchased // data members will go here };

MEMBER VARIABLES TWO NOTIONS OF EQUALITY

Each CashRegister object must store the total price and Shallow equality item count of the sale that is currently rung up Same actual object data in memory Compare only references We store this data as private member variables ==

class CashRegister Deep equality { public: Compare objects’ variable values void clear(); void add_item(double price); Might not have same reference double get_total() const; int get_count() const; Need a separate function for this private: int item_count; Accessible only by object’s double total_price; }; member functions

class KindlyPerson { public: CONTROLLING ACCESS TO OBJECTS string name; double salary; }; Access specifiers define where the variable or function is accessible class EvilDoer { public: can be used from any class public: KindlyPerson enemy; private: can only be used within the class in which it is defined EvilDoer(KindlyPerson e) { enemy = e; Protect data from manipulation, corruption } void sabotageEnemy(){ enemy.salary = 0; } }; int main(){ KindlyPerson bert; EvilDoer ernie; ernie.sabotageEnemy(); }

5 8/12/10

CONTROLLING ACCESS TO OBJECTS IMPLEMENTING THE MEMBER FUNCTIONS

Important to keep variables private, but most functions are public class CashRegister { public: void clear(); void add_item(double price); double get_total() const; Private functions are generally only used for helper functions you int get_count() const; don’t want other classes to have direct access to private: int item_count; double total_price; }; Hide implementation details: Lets us change internal representation without changing interface

IMPLEMENTING THE MEMBER FUNCTIONS IMPLEMENTING THE MEMBER FUNCTIONS

class CashRegister class CashRegister { { public: public: void clear(); void clear(); void add_item(double price); void add_item(double price); double get_total() const; double get_total() const; int get_count() const; int get_count() const; private: private: int item_count; int item_count; double total_price; double total_price; }; };

void CashRegister::add_item(double price) void CashRegister::clear() { { item_count++; item_count = 0; total_price = total_price + price; total_price = 0; } } Specify that a function is a member function in the name

IMPLEMENTING THE MEMBER FUNCTIONS THE CASH REGISTER PROGRAM

class CashRegister // Display the item count and total price of a cash register. { void display(CashRegister reg) public: { void clear(); cout << reg.get_count() << “ $” << reg.get_total() << endl; void add_item(double price); } double get_total() const; int get_count() const; // The main cash register program. private: int main() int item_count; { double total_price; CashRegister register1; }; register1.clear(); register1.add_item(1.95); display(register1); register1.add_item(0.95); display(register1); register1.add_item(2.50); double CashRegister::get_total() const display(register1); { return 0; return total_price; } } int CashRegister::get_count() const { return item_count; }

6 8/12/10

CONSTRUCTORS WHAT HAPPENS HERE?

A constructor is a member function that initializes the data CashRegister register1; register1.add_item(1.95); members of an object int count = get_count(); // What is the count?

The constructor is automatically called when an object is created CashRegister register1;

Constructors are written to guarantee that an object is always fully and correctly initialized when it is defined

THE CONSTRUCTOR THE CONSTRUCTOR

Guarantees that an object’s variables are correctly initialized Guarantees that an object’s variables are correctly initialized Constructor name must match class name Constructor name must match class name No return type No return type Invoked automatically by C++ when a new object is declared Invoked automatically by C++ when a new object is declared (never called directly) (never called directly) class CashRegister class CashRegister CashRegister::CashRegister() { { { public: public: item_count = 0; CashRegister(); // A constructor CashRegister(); total_price = 0; ...... } }; };

PLACEMENT OF main() TWO KINDS OF FILES

Your program may use multiple classes Header .h files (which will be #included) contain the interface: Definitions of classes Defined each class in a separate file Definitions of constants Declarations of nonmember functions

Each program can have only one main() Source .cpp files contain the implementation: Definitions of member functions Choose one class (file) to contain the program’s main() Definitions of nonmember functions

7 8/12/10

TWO KINDS OF FILES DEFINING CLASSES

For the CashRegister class, create a pair of files: In a problem description… Nouns correspond to classes, e.g. paycheck object cashregister.h Verbs correspond to member functions, e.g. compute_taxes() the interface – the class definition

cashregister.cpp the implementation – all the member function definitions

INHERITANCE SUPERCLASS (PARENT OR BASE CLASS)

Create new classes that are based on (or extend) existing classes. The more general class from which other classes inherit

Shape Student Shape Student

Rectangle Circle TuftsStudent Rectangle Circle TuftsStudent

SUBCLASS (CHILD OR DERIVED CLASS) INHERITANCE HIERARCHY

The more specific class that modifies the existing superclass by A superclass can also be a subclass of another class adding new fields or methods modifying (overriding) some methods’ behavior Shape

Shape2D Shape3D Shape Student

Rectangle Circle Cube Sphere

Rectangle Circle TuftsStudent Square

8 8/12/10

INHERITANCE HELPS US… PROGRAMMING MODELS

Factor out common functionality and put it in a superclass Procedural programming Break problem into tasks to be performed Reuse code Write functions to solve simple subtasks and combine them

Write code that more accurately reflects objects’ relationships Object-oriented programming “Is a”: inheritance Break problem into classes or types “Has a”: composition / aggregation Associate functionality with those classes “Uses a”: dependence

WHY CHOOSE ONE OVER THE OTHER?

Depends on the goal of the program

Object-oriented often considered better for large-scale projects working within a team code that will be extended over time

OOP promotes encapsulation, reusability, and allows inheritance

9