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 • 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
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
Object-Oriented Programming (OOP) • A programming paradigm centered on objects (and the interactions between them) rather than actions Song : title artist size MP3 Player lyrics __playCount__ MP3 Player : songs playSong() listOfSongs __songCount__ addSong(Song) Song : playSong(title) addSong() removeSong() title removeSong(title) artist size playSong() lyrics __playCount__ playSong() Procedural OOP 4
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
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
OOP Concepts • Encapsulation : Combining data and the code that operates 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 object 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
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
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 // 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 9
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
Example Class Declaration 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(); }; 11
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
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 int getHour() const; int getMinute() const; int getIsAM() const; • The below function may or may not change the values of member data void addMinute(); 13
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 "get VarName " • (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 "set VarName " 14
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
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 ( :: ) 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 16
Defining Setters & Getters // mutators void Time::setHour(int hr) { if(hr < 1 || hr > 12) { // accessors // Error } int Time::getHour() const { hour = hr; return hour; } } void Time::setMinute(int min) { int Time::getMinute() const { if(min < 0 || min > 59) { return minute; // Error } } minute = min; bool Time::getIsAM() const { } return isAM; } void Time::setAM() { isAM = true; } (this code would be in void Time::setPM() { Time.cpp ) isAM = false; } 17
Defining Other Member Functions // 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++; } 18
Defining Other Member Functions string Time::toString() const { // returns time formatted to (H)H:MM (A/P)M ostringstream 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 } ostringstream allows you to create a string by "outputting" to it with << (exactly as you would to cout ), including I/O formatting must #include <sstream> 19
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 class Time { Time.h private: int hour; int minute; bool isAM; ... public: ... void addMinute(); // adds one more minute void addMinute(int n); // adds n more minutes }; 20
Recommend
More recommend