"A class is where we teach an object how to behave." --Rich Pattis

Slides:



Advertisements
Similar presentations
David Notkin Autumn 2009 CSE303 Lecture 26 If you think C++ is not overly complicated, just what is a protected abstract virtual base pure virtual private.
Advertisements

Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-1: Classes and Objects reading: self-checks: Ch. 8 #1-9 exercises:
Road Map Introduction to object oriented programming. Classes
Terms and Rules Professor Evan Korth New York University (All rights reserved)
1 CSE 303 Lecture 21 Classes and Objects in C++ slides created by Marty Stepp
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Object Oriented Programming Concepts OOP – reasoning about a program as a set of objects rather than as a set of actions Object – a programming entity.
Based on slides at buildingjavaprograms.com Objects and Classes, take 2 Managing Complexity with Programmer-Defined Types  Classes are programmer-defined.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 4 – August 30, 2001.
CS 106X Classes and Objects
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
CS305j Introduction to Computing Classes 1 Topic 23 Classes – Part I "A 'class' is where we teach an 'object' to behave." -Rich Pattis Based on slides.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Topic 27 classes and objects, state and behavior Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
Chapter 2 Objects and Classes
Programming Abstractions
Pointer to an Object Can define a pointer to an object:
Procedural and Object-Oriented Programming
Creating and Using Objects, Exceptions, Strings
Object Oriented Programming
Classes C++ representation of an object
Building Java Programs
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Classes and OOP.
Chapter 7: Introduction to Classes and Objects
Abstract Data Types Programmer-created data types that specify
10.2 Classes Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
Review: Two Programming Paradigms
Introduction to Classes
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
CMPE Data Structures and Algorithms in C++ February 22 Class Meeting
suggested reading: Java Ch. 6
This pointer, Dynamic memory allocation, Constructors and Destructor
The dirty secrets of objects
Classes and Objects, State and Behavior
Introduction to Classes
Building Java Programs
Chapter 9 Objects and Classes
Classes Short Review of Topics already covered Constructor
A programming problem Given a file of cities' (x, y) coordinates, which begins with the number of cities: Write.
Chapter 8 Lecture 8-1: Classes and Objects
Building Java Programs
Building Java Programs
Building Java Programs
A programming problem Given a file of cities' (x, y) coordinates, which begins with the number of cities: Write.
Building Java Programs
Building Java Programs
Classes C++ representation of an object
Classes and objects Readings: 8.1.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Lecture 8 Object Oriented Programming (OOP)
Classes and Objects Object Creation
Building Java Programs
Building Java Programs
CMSC 202 Constructors Version 9/10.
Presentation transcript:

"A class is where we teach an object how to behave." --Rich Pattis Classes and Objects "A class is where we teach an object how to behave." --Rich Pattis

C++ Classes Classes are programmer-defined types Classes help us manage complexity, since they: tie together related data and operations decompose an application into objects and their interactions can be re-used in different applications Example: string class data: sequences of characters operations: length(), append(), insert(), etc. general description or blueprint of a collection of objects, such as "Charlie", and operations that I can invoke on those objects string myDogsName = "Charlie"; // a string object, a instance of string class Call string functions on the object: myDogsName.append(" Boy");

Calendar Program Want to write program that manipulates dates Calendar application, program that stores birthdays, etc. No C++ type that represents dates What is today's date? 10 30 What is your birthday: 11 3 It is 4 days until your next birthday. So: write a Date class so that each object represents a date like October 30. What data and operations should a Date object have?

Date – client code #include<iostream> #include "Date.h" int main() { Date today(10, 30); Date halloween(10, 31); cout << "Today is: " << today.toString() << ", the month is: " << today.getMonth() << endl; }

Classes and Objects class: a blueprint or template for a new type of objects object: an entity in your program that combines state and behavior object-oriented programming (OOP): programs that perform their behavior as interactions between objects

Blueprint analogy creates iPod blueprint state: current song volume battery life behavior: power on/off change station/song change volume choose random song creates iPod #1 state: song = "1,000,000 Miles" volume = 17 battery life = 2.5 hrs behavior: power on/off change station/song change volume choose random song iPod #2 state: song = "Letting You" volume = 9 battery life = 3.41 hrs iPod #3 state: song = "Discipline" volume = 24 battery life = 1.8 hrs

Abstraction abstraction: A distancing between ideas and details. We can use objects without knowing how they work. Objects provide abstraction in programming. abstraction in an iPod: You understand its external behavior (buttons, screen). You don't understand its inner details, and you don't need to, in order to use an iPod.

Class Design We will implement a Date class, i.e., a type of objects named Date Each Date object will contain month, day variables called fields or member variables Each Date object will contain behavior called member functions or methods Client programs will use the Date objects. To create a new class, think about the objects that will be created of this new class type: what information to store about the object what behavior the object has

In a Class instance variables or fields: the state/data of an object each object has its own copy of each field private: not accessible outside the class also known as instance variables member functions: the behavior of an object also called methods methods can operate on the data in the object constructor: special method called when object is created initializes the state of the new object, often using the constructor's arguments has the same name as the class

Client, Class and Object Use class to construct new objects Client Program int main() {... - uses class and objects Class - defines data in each object -how to construct new objects send/receive messages to/from objects by calling member functions constructs Object -member functions (behavior) fun1() fun2() -member variables (data) object object

C++ Date Class #include "Date.h" Date::Date(int m, int d) { month = m; day = d; } int Date::getMonth() const { return month; int Date::getDay() const { return day; int Date::daysInMonth() const { if(month == 4 || month == 9 || month == 6 || month == 11){ return 30; } else if(month == 2) return 28; else return 31; void Date::nextDay() { day++; if(day > daysInMonth()) { day = 1; month++; if(month > 12) month = 1;

Interface and Implementation C++ classes: interface: declaration of functions, classes, members, etc. implementation: definitions – how the things in interface are implemented Separated into two types of files header ClassName.h file contains the interface source ClassName.cpp file contains definitions – the implementation For class Date, write Date.h and Date.cpp In Date.cpp: #include "Date.h" No main function in either file

.h File // yourClass.h #ifndef _classname_h #define _classname_h class declaration #endif Possibly multiple .cpp files will include the header file. This prevents the contents getting declared twice.

Class Declaration class ClassName { public: ClassName(parameter-list); // constructor type name1(parameter-list); // member functions type name2(parameter-list); private: type name; // member variables type name; };

Date.h #ifndef _date_h #define _date_h class Date { public: Date(int m, int d); // constructor int daysInMonth(); int getMonth(); int getDay(); void nextDay(); string toString(); private: int month; int day; }; // must have ; #endif

Encapsulation encapsulation: hiding implementation details of class from clients protects data from manipulation by client Ex: client cannot change month field in Date object to 20 Class data fields should be declared private access permitted only through member functions code outside class cannot access them private: type fieldName;

Member Definitions (.cpp file) ClassName.cpp: contains function definitions for member functions that were declared in header file #include "ClassName.h" type ClassName::functionName(parameter-list) { // function stuff } Not any old function – part of my class

Implementation, cont'd #include "Date.h" Date::Date(int m, int d) { month = m; day = d; } // write getMonth() function here... ...

Date Class int Date::getMonth() { // in Date.cpp return month; } // client code Date today; Date halloween; ... int mo = today.getMonth(); halloween.getMonth(); today month day int Date::getMonth() { return month; } 10 30 halloween month day int Date::getMonth() { return month; } 10 31

Client Code #include<iostream> #include "Date.h" using namespace std; int main() { Date date1(10, 30); Date date2(10, 31); Date examDate(12, 15); cout << "date1 is: " << date1.getMonth() << "\" << date1.getDay() << endl; } const – doesn't change the date (state of date) – ie, doesn't change fields day, month Promise that calling function doesn't modify the date fields

Operator Overloading Overload the behavior of operators in C++ + - ++ * & ! % > Don't overuse – can produce confusing code Declare operator in .h file, implement in .cpp return operator op(parameter-list); // .h return operator or(parameter-list) { // .cpp statements; }

Operator Overloading In Date.cpp bool operator ==(const Date& d1, const Date& d2) { return d1.getMonth() == d2.getMonth() && d1.getDay() == d2.getDay()); } Exercise: Overload < for Dates: if a Date comes earlier in the year, it's less than another Date Exercise: Overload <= and != for Date class

Point Class Represents points in 2D space The class is a blueprint that describes how to create objects We will define a type called Point Each object has its own data/state and methods State of a Point object (i.e., member variables)? Behavior of a Point object (i.e., member functions)?

Point Class: a new type Represents any point in 2D space State of a Point object: x and y fields Behavior of a Point object: accessors that return the value of each field compute distance of Point object to the origin (0, 0) mutators that change the value of a field update the Point object's location (change x and y fields)

Point.h #ifndef _POINT_H #define _POINT_H class Point { private: int x; int y; public: Point(int x, int y); int getX(); // accessor/getter int getY(); double distance(Point& p); void setLocation(int x, int y); }; #endif

Point.cpp #include "Point.h" Point::Point(int x, int y) { this->x = x; this->y = y; } // fill in the rest parameter this is a pointer to the current object (has type const Point *) can be used to distinguish between member variables and parameters with the same name Each member is defined on its own using :: scope operator to indicate the class name

implicit parameter implicit parameter: the object on which a member function is called date1.getMonth(); object called date1 is the implicit parameter Member function refers to that object's member variables Acts like each object has its own copy of the member functions this: pointer to the object on which member function is called this  month;

Class Terminology accessor methods (aka getters): methods that return value of an instance variable naming convention: getInstanceVariable() Ex: For Date class: getMonth(), getDay() mutator methods (aka setters): methods that modify the value of an instance variable naming convention: setInstanceVariable() Ex: For Date class: setMonth(), setDay() Do these defeat the purpose of making instance variables private? friend: Designate a function as a friend of a class – then it can access the private instance variables directly friend bool operator ==(Date &d1, Date & d2) { // in Date.cpp file return d1.month == d2.month && d1.day == d2.day; }

Exercise Modify the class so that a Point can be constructed with no parameters, in which case it's initialized to represent (0, 0) Write a translate member function that shifts the position of a Point by specified values in x and y direction Overload the == operator for Point

Constructors initialization list: a different way to initialize member variables Class::Class(parameter-list) : field(param), ..., field(param) { //statements } Date::Date(int m, int d) : month(m), day(d) { ... default constructor: if no constructors provided, a default no-arg constructor is automatically provided sets all fields to 0 for their type (0, 0.0, NULL, false...) Multiple constructors: can't call each other

malloc vs. new Used to allocate memory for: malloc: any type new: arrays, structs, objects What happens when memory runs out? malloc: returns NULL new: throws an exception How to deallocate: malloc: free new: delete (or delete [])

Arrays Allocated on stack: type name[size]; Allocated on heap: type* name = new type[size]; Example: int* numbers = new int[5]; for(int i = 0; i < 5; i++) { numbers[i] = 2 * i; } ... delete [] numbers;

Creating Instances/Objects Creating an object on runtime stack: type name(parameter-list); Date date1(9, 11); cout << date1.getMonth(); Creating object on heap: type* name = new type(parameter-list); Date* date2 = new Date(10, 30); cout << date2  getMonth(); delete date2; // free memory

Objects: Stack or Heap? Heap: Stack: if it needs to exist after function returns to allocate a bunch of objects new: allocates memory for new object, calls class constructor, returns pointer to new object call delete on anything you allocate with new Stack: semantics a bit simpler a stack-allocated object is copied when you pass it as an argument foo(date1); return it return date1; assign one object to another d = date1;

Object Parameters Usually don't want to copy objects when they are passed: double Point::distance(Point p) { int dx = x - p.getX(); int dy = y – p.getY(); return sqrt(dx*dx + dy*dy); } Every time distance is called, argument copied into parameter Slow & wastes memory Can't modify argument

Object Reference Parameter Pass a reference or pointer to object instead double Point::distance(Point& p) { int dx = x - p.getX(); int dy = y – p.getY(); return sqrt(dx*dx + dy*dy); } Now parameter and argument reference same memory Better to make parameter const – distance method guarantees it doesn't modify p double Point::distance(const Point& p) {... Clients know which methods modify arguments

const method If method does not modify the object it's invoked on, make it const double Point::distance(Point& p) const { int dx = x - p.getX(); int dy = y – p.getY(); return sqrt(dx*dx + dy*dy); } Placing const after parameter list indicates that method does not modify object it's called on

Oy, const and pointers (aka C++, why do you hate me?) const Point *p p points to a const Point (a Point with state that cannot be changed) p can be reassigned to point to another const Point Point * const p p is a constant pointer – p can't be reassigned to point at another object the Point's state can be changed const Point * const p p is a constant pointer that points to a constant Point cannot reassign p to point at a different object cannot modify the Point's state Note: object fields are usually pointers, not references. Recall that references must be initialized when declared, cannot be reassigned, and cannot be NULL.

Exercise: BankAccount Class State? name of account holder, balance Behavior? accessor methods, withdraw, deposit Constructors: two argument constructor, one argument constructor (which takes name and sets balance to 0) Overload: ==, !=,

Exceptions exception: an error represented as an object C handles errors by returning error codes C++ can represent errors as exceptions that are thrown/caught Throwing exception: Syntax: throw expression; Generates an exception that will crash the program, unless there is matching code to handle the error (i.e., "catch" the exception) // pre: balance is non-negative BankAccount::BankAccount(string name, double balance) { if(balance < 0) { throw "Illegal negative balance"; } this  name = name; this  balance = balance; Can throw anything: string, int, etc. Can make exception class if you want to throw lots of info: #include<exception> Exceptions are runtime errors. Caused by exceptional circumstances: unable to open file, running out of memory, out of bounds index on vector using at() If a function cannot "handle" or catch the exception, it throws the exception and expects the caller to handle it.

Exceptions catching an exception with a try/catch block: try { if(n < 0) throw n; double answer = sqrt(n); cout << answer << endl; } catch (double d) { cout << "Cannot take sqrt of " << d << endl; }