Introduction to Classes Gaddis Ch. 13 CS 2308 :: Spring 2016 Molly - - PowerPoint PPT Presentation

introduction to classes
SMART_READER_LITE
LIVE PREVIEW

Introduction to Classes Gaddis Ch. 13 CS 2308 :: Spring 2016 Molly - - PowerPoint PPT Presentation

Introduction to Classes Gaddis Ch. 13 CS 2308 :: Spring 2016 Molly O'Neil Procedural Programming Programming paradigm centered on the actions that take place in a program Data is stored in variables Perhaps using arrays and structs


slide-1
SLIDE 1

Introduction to Classes

Gaddis Ch. 13 CS 2308 :: Spring 2016 Molly O'Neil

slide-2
SLIDE 2

Procedural Programming

  • Programming paradigm centered on the actions that

take place in a program

  • Data is stored in variables
  • Perhaps using arrays and structs
  • Program is a collection of functions that operate on

the variables

  • Example: the MP3 Player assignment
  • Data is passed to the functions as arguments

2

slide-3
SLIDE 3

Issues with Procedural Programming

  • Program specifications change
  • Representations of data change
  • If data and functionality are separated (with one

passed to the other to be operated on), it quickly becomes difficult to manage these changes

  • A change to a data structure requires changes to all

functions that operate on that data structure

  • What if those functions were being re-used for other data

structures that no longer look similar?

  • Lots of work to make changes, lots of room for bugs
  • Example: Re-implement MP3 player using C++ STL's

vector instead of an array

3

slide-4
SLIDE 4

Object-Oriented Programming (OOP)

  • A programming paradigm centered on objects (and the

interactions between them) rather than actions

4

addSong() playSong() removeSong()

songs

MP3 Player:

listOfSongs __songCount__ addSong(Song) playSong(title) removeSong(title)

Song:

title artist size lyrics __playCount__ playSong()

Song:

title artist size lyrics __playCount__ playSong()

MP3 Player

Procedural OOP

slide-5
SLIDE 5

Objects

  • An object is defined by its:
  • Attributes (things about the object)
  • Actions (things the object can do)
  • Attributes: a particular Car might be red, a Honda, a

Civic, a stick-shift, and have 78,421 miles on it

  • The object Car therefore has the attributes color, make,

model, transmission, and mileage

  • All objects of type Car have these attributes; they do not all

have the same values for the attributes

  • Actions: a Car can drive forward 100 feet, stop, back

up 10 feet, etc.

5

slide-6
SLIDE 6

Objects in Code

  • An object has:
  • Member Data (like the fields of a struct) [Attributes]
  • Member Functions (that operate on that data) [Actions]
  • Called methods in other OOP languages
  • Code outside of the object can access the object's

data only through the object's (public) functions

  • If the representation of the data inside the object needs

to change...

  • Only the object's function definitions must be redefined
  • The code outside the object doesn't need to change; it still

accesses the object in the same way

6

slide-7
SLIDE 7

OOP Concepts

  • Encapsulation: Combining data and the code that
  • perates on that data into a single object
  • Data hiding: The ability to hide the details of the data

representation (particular data structures, how the functions implement their behavior [e.g., which sort algorithm], etc.) from code outside the object

  • Interface: The mechanism that code outside the
  • bject uses to interact with the object
  • The object's (public) functions
  • Outside code (or its author) only needs the function

prototype; doesn't need to know the details of the function body

7

slide-8
SLIDE 8

Interface Example

  • To drive a car, you only need to understand and

interact with its interface

  • Ignition switch
  • Gas pedal
  • Brake pedal
  • Steering wheel
  • Gear shifter
  • You don't need to understand how the steering works

internally, or whether or not the engine has spark plugs

  • You can operate any car with the same interface

8

slide-9
SLIDE 9

Classes and Objects

  • A class is a blueprint for an object
  • Defines the attributes (member data) and actions (functions/

methods) shared by all objects of the class

  • Used to make many objects
  • These objects are called instances of the class
  • Each instance has its own copies of all of the member variables
  • One car can be green, one car can be blue, but both cars have a color
  • You already know one class: string

9

// create two string instances string cityName1 = "Austin", cityName2 = "San Marcos"; // use the string class's member functions int size = cityName1.length(); cityName2.append(", TX");

  • Note the . operator to access member functions
slide-10
SLIDE 10

C++ Classes

  • A C++ class is similar to a struct
  • Allows you to define a new (composite) data type
  • (Public) members (data or functions) accessed with the dot

(.) operator

  • Unlike a struct, a class also has member functions

(things objects of the class can do)

  • A class declaration defines:
  • Member variables (the data)
  • Member functions (that operate on the data)
  • Class declaration must define at least the prototype, function

body can be defined elsewhere

10

slide-11
SLIDE 11

Example Class Declaration

11

class Time { private: int hour; int minute; bool isAM; void addHour(); public: // accessors int getHour() const; int getMinute() const; bool getIsAM() const; // mutators void setHour(int); void setMinute(int); void setAM(); void setPM(); string toString() const; void addMinute(); };

slide-12
SLIDE 12

Access Specifiers

  • Used to control access to members of the class
  • public: can be accessed or called by code outside of the class
  • private: can only be accessed or called by code within the

class (i.e., functions that are members of the class)

  • Can be listed in any order, and can appear multiple times in

a class declaration

  • If not specified, the default is private
  • Member variables should be declared private, to hide

their definitions from outside the class

  • Some functions are declared public to provide (controlled)

access to the hidden/private data

  • These public functions form the interface to the class
  • Some internal helper functions may be private

12

slide-13
SLIDE 13

Using const with Member Functions

  • The const after the parentheses in a member function

declaration declares that the function will not modify any of the object's member variables

  • The below member functions guarantee they do not

change the values of hour, minute, or isAM

  • The below function may or may not change the values
  • f member data

13

int getHour() const; int getMinute() const; int getIsAM() const; void addMinute();

slide-14
SLIDE 14

Accessors & Mutators ("Getters" & "Setters")

  • Accessor functions
  • Return a value from the object (without changing it)
  • A getter returns the value of a single member variable
  • By convention, generally named "getVarName"
  • (Remember, code outside the class can't just access the

variables via the dot operator, because they're private - must access through the public interface)

  • Mutator functions
  • Modify the value(s) of member variable(s)
  • A setter sets/modifies the value of a single member variable
  • By conventionally, generally named "setVarName"

14

slide-15
SLIDE 15

Separating Specification from Implementation

  • Class declarations are usually located each in its own

header file (e.g., Time.h)

  • Called the class specification file
  • Filename usually the same as the class name
  • Member function definitions are stored in a separate file

(e.g., Time.cpp)

  • Called the class implementation file
  • This file must #include the class's header file
  • Any program/file using the class must include the class

specification file (the header file)

  • #include "Time.h"

15

slide-16
SLIDE 16

Defining Member Functions

  • Member functions must be (at least) prototyped in

class declaration

  • Member function definitions usually occur outside of

the class (and usually in a separate file)

  • The name of each function is preceded by the class

name, followed by the scope resolution operator (::)

16

void Time::setHour(int hr) { if(hr < 1 || hr > 12) {
 // Error
 } hour = hr; }

Note that at first glance, hour above looks undeclared! It refers to the member variable of the Time class

slide-17
SLIDE 17

Defining Setters & Getters

17

// accessors int Time::getHour() const { return hour; } int Time::getMinute() const { return minute; } bool Time::getIsAM() const { return isAM; } // mutators void Time::setHour(int hr) { if(hr < 1 || hr > 12) { // Error } hour = hr; } void Time::setMinute(int min) { if(min < 0 || min > 59) { // Error } minute = min; } void Time::setAM() { isAM = true; } void Time::setPM() { isAM = false; }

(this code would be in
 Time.cpp)

slide-18
SLIDE 18

Defining Other Member Functions

18

// private member functions void Time::addHour() { if(hour == 12) { hour = 1; isAM = !isAM; } else hour++; } // public member functions void Time::addMinute() { if(minute == 59) { minute = 0; addHour(); // call to private member function } else minute++; }

slide-19
SLIDE 19

Defining Other Member Functions

19

string Time::toString() const { // returns time formatted to (H)H:MM (A/P)M

  • stringstream strstr;

strstr.fill('0'); // sets the padding char for setw strstr << hour << ":" << setw(2) << minute; strstr << (isAM ? " AM" : " PM"); return strstr.str(); // returns the stream's string }

  • stringstream allows you to create a string by

"outputting" to it with << (exactly as you would to cout), including I/O formatting must #include <sstream>

slide-20
SLIDE 20

Overloaded Member Functions

  • Recall that 2 or more functions can have the same

name, as long as they have different parameter lists

  • The functions are overloaded
  • Class member functions can also be overloaded

20

class Time { private: int hour; int minute; bool isAM; ... public: ... void addMinute(); // adds one more minute void addMinute(int n); // adds n more minutes };

Time.h

slide-21
SLIDE 21

Inline Member Functions

  • Occasionally (for very short functions) it is appropriate to

define a class member function inline (inside the class declaration, rather than outside the class)

21

class Time { private: int hour; int minute; // ... public: // accessors int getHour() const { return hour; } int getMinute() const { return minute; } // mutators void setHour(int hr) { hour = hr; } void setMinute(int min) { minute = min; } void addMinute(); // NOT INLINE // ... };

Time.h

slide-22
SLIDE 22

Declaring an Instance of the Class

  • Just like a struct:

22

Time t1;

  • This defines t1 to be an object of type Time
  • t1 has member variables hour, minute, and isAM
  • Access public members of class with dot operator:

t1.setHour(3); t1.setMinute(42); t1.setIsPM();

  • The above code is outside the class, so must use dot
  • perator to access class members through the public

interface

slide-23
SLIDE 23

Using the Time Class

23

int main() { Time t; t.setHour(11); t.setMinute(58); t.setPM(); cout << t.toString() << endl; t.addMinute(); cout << t.toString() << endl; t.addMinute(); cout << t.toString() << endl; return 0; } 11:58 PM 11:59 PM 12:00 AM

Output:

slide-24
SLIDE 24

Constructors

  • Often, we want to initialize at least some of an object's

member variables as soon as it's created

  • What happens if we run the following code?

24

Time t1; cout << t1.getHour();

  • A constructor is a member function of a class that is

called automatically when an object is created

  • Its function name is the same as the class name
  • It has no return type
  • It is responsible for initializing the new object

class Time { public: Time(); // constructor prototype };

slide-25
SLIDE 25

Constructor Definition

25

#include <sstream> #include <iomanip> #include "Time.h" using namespace std; Time::Time() { // initializes hour, minute, and isAM hour = 12; minute = 0; isAM = true; }

Note that the constructor function has no return type Name of constructor function is just the name of the class ( still need the ClassName:: before the definition)

Time.cpp

slide-26
SLIDE 26

Constructor Call

26

#include <iostream> #include "Time.h" using namespace std; int main() { Time t; // constructor called implicitly here cout << t.toString() << endl; t.addMinute(); cout << t.toString() << endl; } 12:00 AM 12:01 AM

Output:

slide-27
SLIDE 27

Constructors with Parameters

  • You can also define a constructor that takes arguments
  • For example, to initialize member variables to specific values

27

class Time { private: ... public: Time(int, int, bool); // constructor prototype ... }; Time::Time(int hr, int min, bool am) { if(hr < 1 || hr > 12 || min < 0 || min > 59) { // Error } hour = hr; minute = min; isAM = am; }

Time.cpp Time.h

slide-28
SLIDE 28

Passing Arguments to Constructors

  • Pass arguments to the constructor when you create a

new object (in the declaration)

  • Use parentheses after the variable name

28

int main() { Time t(10, 59, false); cout << t.toString() << endl; } 10:59 PM 11:00 PM

Output:

slide-29
SLIDE 29

Multiple (Overloaded) Constructors

  • You can define as many

class constructors as you like, as long as they all have unique parameter lists

29

Time::Time() { hour = 12; minute = 0; isAm = true; } Time::Time(int hr, int min, bool am) { if(hr < 1 || hr > 12 || min < 0 || min > 59) { // Error } hour = hr; minute = min; isAM = am; } Time::Time(int hr) { if(hr < 1 || hr > 12) // Error hour = hr; minute = 0; isAM = true; } class Time { private: ... public: Time(); Time(int, int, bool); Time(int); ... };

Time.h Time.cpp

slide-30
SLIDE 30

Overloaded Constructor Calls

30

int main() { Time t1; Time t2(5, 28, false); Time t3(2); cout << t1.toString() << endl; cout << t2.toString() << endl; cout << t3.toString() << endl; } 12:00 AM 5:28 PM 2:00 AM

Output:

slide-31
SLIDE 31

Default Constructors

  • A default constructor is a constructor that takes no

arguments (e.g., Time())

  • If you write a class and do not declare any

constructors, the compiler will include an implicit default constructor for you

  • The constructor does (essentially) nothing, initializes none of

the member variables

  • Our original version of the Time class did not define a

constructor, so the compiler provided one

31

Time t1; Time t2(); // both use the default constructor

slide-32
SLIDE 32

Classes with No Default Constructor

  • If all of a class's constructors require arguments (i.e.,

there is no default constructor), then the compiler does not create an implicit default constructor

  • In other words, you must pass the required arguments to the

constructor in order to instantiate an object

  • Useful for preventing creation of object with uninitialized

member variables

32

class Time { public: Time(int, int, bool); // the only constructor }; int main() { Time t1(10, 0, true); // OK Time t2; // NOT OK - DOES NOT COMPILE }

slide-33
SLIDE 33

Destructors

  • Member function that is called automatically when an
  • bject is destroyed
  • Either because it's a local variable and goes out of scope
  • Or because it was dynamically allocated and is deleted
  • Destructor name is ~ClassName, e.g., ~Time
  • Has no return type, takes no arguments
  • Only one destructor per class
  • Since it has no parameters, it cannot be overloaded
  • If the class dynamically allocates memory, the

destructor should delete the allocation(s)

33

slide-34
SLIDE 34

Destructor Example

  • Example: MP3 Player class, with dynamically allocated

array of Song structs

34

struct Song { string title; string artist; double size; }; class MP3Player { private: Song *songs; // ptr for dynamically allocated array double maxMB; int maxSongs; int count; public: MP3Player(int, double); // no default constructor ~MP3Player(); bool addSong(Song); ... };

MP3Player.h

slide-35
SLIDE 35

Destructor Example

  • Member function definitions for constructor and

destructor:

35

#include "MP3Player.h" MP3Player::MP3Player(int numSongs, double numMB) { songs = new Song[numSongs]; // dynamic allocation maxSongs = numSongs; maxMB = numMB; count = 0; } MP3Player::~MP3Player() { delete [] songs; }

MP3Player.cpp

slide-36
SLIDE 36

Calling the Destructor

  • Example driver creates and destroys an MP3Player:

36

#include <iostream> #include "MP3Player.h" using namespace std; int main() { MP3Player player(50, 25.0); // calls constructor // do stuff with player here return 0; // main goes out of scope, player object is } // destroyed here, its destructor is called // (which deletes the internal songs array)

  • Same as with a constructor, you are not required to

define a destructor. However, any time your class dynamically allocates, you must have a destructor to avoid memory leaks!

slide-37
SLIDE 37

Arrays of Objects

  • Objects can be the elements of an array:

37

int main() { Time recentCalls[10]; // times of last 10 calls }

  • Default constructor (Time()) is used to initialize each

element of the array when it is created

  • This array is initialized to 10 Time objects, each set to

12:00 AM.

slide-38
SLIDE 38

Arrays of Objects

  • To invoke a constructor that takes a single argument,

you can use an initialization list:

38

int main() { Time recentCalls[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; }

  • The constructor that takes one argument is used to

initialize each of the 10 Time objects above

  • This array is initialized to 10 Time objects, set to 1:00

AM, 2:00 AM, 3:00 AM, 4:00 AM, etc.

slide-39
SLIDE 39

Arrays of Objects

  • If the constructor requires more than one argument, the

initializer must take the form of a function call to the constructor:

39

int main() { Time recentCalls[5] = { Time(8, 5, true), Time(9, 12, true), Time(11, 21, true), Time(12, 1, false), Time(12, 57, false) }; }

  • This array is initialized to 5 Time objects, set to 


8:05 AM, 9:12 AM, 11:21 AM, 12:01 PM, 12:57 PM

slide-40
SLIDE 40

Arrays of Objects

  • It isn't necessary to call the same constructor for each
  • bject in an array

40

int main() { Time recentCalls[7] = { 8, Time(9, 12, true), 11, Time(12, 1, false), Time(12, 57, false) }; Time recentDeliveries[5] = { Time(), Time(10), Time(10, 43, true), Time(), Time(12, 30, false) }; }

  • If there are fewer initializers in list than elements in

array, the default constructor will be called for all the remaining elements

slide-41
SLIDE 41

Accessing Objects in an Array

  • Objects in an array are referenced using subscripts

(just like any other element of an array)

  • Member functions are referenced using the dot
  • perator

41

recentCalls[2].addMinute(); cout << recentCalls[4].toString() << endl;

  • Just like when accessing fields of a struct that's an

element of an array, we must access the specific

  • bject (apply brackets) before calling the member

function (applying the dot operator)