Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: ""A class is where we teach an object how to behave." --Rich Pattis"— Presentation transcript:

1 "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

2 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");

3 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?

4 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; }

5 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

6 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

7 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.

8 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

9 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

10 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

11 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;

12 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

13 .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.

14 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; };

15 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

16 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;

17 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

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

19 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

20 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

21 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; }

22 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

23 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)?

24 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)

25 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

26 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

27 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;

28 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; }

29 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

30 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

31 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 [])

32 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;

33 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

34 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;

35 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

36 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

37 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

38 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.

39 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: ==, !=,

40 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.

41 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; }


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

Similar presentations


Ads by Google