View
217
Download
0
Embed Size (px)
Citation preview
Engineering Problem Solving With C++
An Object Based Approach
Chapter 8
Introduction to Classes
Classes
• The building blocks of object oriented programming
• Include function members and data members
• A well designed class is as easy to use as a pre-defined data type
Designing a Class
• Desired operations– Member functions or methods
• constructors• accessor functions• overloaded operators• … (functions that do the “work”)
• Required data members
Writing a Class Definition
• A class definition has two parts– Class declaration
• defines name of class, data members, and prototypes for member functions
– Class implementation• implements the member functions
Class Declaration
• Name of the class is specified using the key word class
• Body of the class declaration includes– declaration statements for the data members– function prototypes
• Keywords public, private and protected specify the accessibility of the class members
Example - Date Class Declaration
#include <iostream>using namespace std;class Date{ //class body
public: void input(istream&); // I/O methods
void print(ostream&) const;void setDate(int mo, int d, int y);int get_day() const; // access methodsint get_month() const;int get_year() const;
private:int day, month, year;
};
Date Class
• Name of the class is Date
• Three private data members
• Six public function members
• Data members can only be accessed by the member functions
Class Implementation
• Includes– Function definitions for all function members– Scope Resolution Operator (::) specifies a
function as a member of a class
Implementation of Date Class
#include “Date.h”…void Date::input(istream& in){ in >> month >> day >> year;}void Date::print(ostream& out) const;{ out << month <<‘/’ <<day << ‘/’ << year;}void Date::set_date(int m, int d, int y){ month = m;
day = d;year = y;
}
Accessor Functions
• Required to access private data members• Complete set should be provided• Our Date class requires 3 accessor functions
int get_day() const;
int get_month() const;
int get_year() const;const should be placed at the end of any function that is not intended to modify the calling object.
Initializing Objects
• Constructor functions are used to initialize objects at the time they are declared– Called automatically– Same name as the class name– No return value, not even void
Constructors for the Date Class
• Default Constructor– constructor with no parameters– Prototype:
Date();
• Constructor with Parameters– Prototype:
Date(int m, int d, int y);
Default Constructor
• Definition:Date::Date() : month(1), day(1), year(2002){ }
• orDate::Date(){ month = 1;
day = 1; year = 2000;
}• First definition is preferred.
Constructors With Parameters
• DefinitionDate::Date(int m, int d, int y):month(m),
day(d), year(y){ }
• orDate::Date(int m, int d, int y){ month = m;
day = d;year = y;
}
Using Programmer Defined Classes
• Separate Compilation– Class declaration is saved in a file named classname.h
– Class implementation is saved in a file named classname.cpp (or whatever extension your compiler expects)
– .h file is included in user program and implementation file
– User program is linked to implementation file
Using the Date Class
#include “Date.h”int main(){ Date today(4,6,2002), birthday; //member functions are called using the dot
operatorbirthday.input(cin);today.print(cout);birthday.print(cout);
if(today.get_day() == birthday.get_day() && today.get_month() == birthday.get_month() ) cout << “happy birthday!”
Practice!
Given this definition of a class for a rational number implement the default constructor, parameterized constructor, and the input function.
class rational{ private:
int num, denom;public: rational( ); // initialize to 1/1
rational(int n, int d);void input (istream & istr ) const;void output (ostream & ostr); // write as
num/denombool improper() const; // true if num >=
denom};
Answer to practice!
#include "rational.h"rational::rational( ):num(1),denom(1) { }rational::rational(int n, int d):num(n),denom(d){ }void rational::input (istream & istr ){ istr >> num >> denom;}
Operators
• Assignment operator is defined for objects of the same typeDate d1, d2;d1.input(cin);d2 = d1;
• Other operators are not predefined, but can be overloaded in the class definition(see chapter 10)– arithmetic, relational, logical, input and output
Helper Functions
• Member functions
• Called by other member functions
• Usually specified as private
Example
Design a class to implement a unit vector. A vector object will be represented by an anchor point (the base of the arrow), and an orientation(always between 0 and 360 degrees). There are 2 manipulations that you can perform on a vector without changing its length.
•translate (slide) the vector in the plane, changing its position but not its orientation. •rotate a vector, changing its orientation
Translation - change position but not orientation
Rotation - change orientation around anchor point
Class Declaration
class UnitVector { public: UnitVector(); // contstructors UnitVector(double init_x, double init_y, double
init_orientation); void rotate(double d_orient); // rotate the vector
void translate(double dx, double dy); // translate the // vector.
private: //helper function void fix_orientation(); // Calculate a legal orientation double x, y; // The anchor point of the object.
int orientation; //orientation};
Class Implementation
//Constructor functionsUnitVector::UnitVector(double initial_x, double
initial_y, double initial_orientation) : x(initial_x), y(initial_y), orientation(initial_orientation)
{fix_orientation();
}UnitVector::UnitVector( ):
x(0), y(0), orientation = 0;{ }
Member Function Definitions
// rotate the calling vectorvoid UnitVector::rotate(double d_orient) { orientation += d_orient;
fix_orientation();}// translate the calling vector void UnitVector::translate(double dx, double dy){ x += dx;
y += dy;}
Helper Function Definition
//This function adjusts the orientation value //Original orientation may be < 0 or >= 360) //Adjusted orientation is 0<=orientation < 360. void UnitVector::fix_orientation() {
if(orientation < 0) orientation = 360 + orientation%360;
elseorientation = orientation%360;
}
Passing Objects To Functions
• Objects may be passed either "by value" or "by reference"
• Example:
bool UnitVector::ShareBasePoint(UnitVector v)const( if (x == v.x && y == v.y)
return true;else
return false;}
Practice!
Which of the statements on the right is valid within a main program which contains an include for this header file.
class rational{ private:
int num, denom; int LCD( );public: rational( ); rational(int n, int d); void input (istream & istr ); void output (ostream & ostr) const; void reduce ( );
};
rational A;rational B(5, 9);input(A);B.output(cout);int div=B.LCD();A.denom = 3;B.reduce;