29
Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

  • View
    217

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

Engineering Problem Solving With C++

An Object Based Approach

Chapter 8

Introduction to Classes

Page 2: 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

Page 3: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

Designing a Class

• Desired operations– Member functions or methods

• constructors• accessor functions• overloaded operators• … (functions that do the “work”)

• Required data members

Page 4: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

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

Page 5: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

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

Page 6: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

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;

};

Page 7: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

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

Page 8: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

Class Implementation

• Includes– Function definitions for all function members– Scope Resolution Operator (::) specifies a

function as a member of a class

Page 9: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

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;

}

Page 10: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

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.

Page 11: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

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

Page 12: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

Constructors for the Date Class

• Default Constructor– constructor with no parameters– Prototype:

Date();

• Constructor with Parameters– Prototype:

Date(int m, int d, int y);

Page 13: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

Default Constructor

• Definition:Date::Date() : month(1), day(1), year(2002){ }

• orDate::Date(){ month = 1;

day = 1; year = 2000;

}• First definition is preferred.

Page 14: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

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;

}

Page 15: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

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

Page 16: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

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!”

Page 17: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

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

Page 18: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

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

Page 19: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

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

Page 20: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

Helper Functions

• Member functions

• Called by other member functions

• Usually specified as private

Page 21: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

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

Page 22: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

Translation - change position but not orientation

Page 23: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

Rotation - change orientation around anchor point

Page 24: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

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

Page 25: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

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

Page 26: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

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

Page 27: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

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;

}

Page 28: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

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

Page 29: Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes

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;