Objects and Classes in C++

92
1 Objects and Classes in C++ Lesson #4 Note: CIS 601 notes were originally developed by H. Zhu for NJIT DL Program. The notes were subsequently re M. Deek.

description

Objects and Classes in C++. Lesson #4. Note: CIS 601 notes were originally developed by H. Zhu for NJIT DL Program. The notes were subsequently revised by M. Deek. Content. Class/Object Definition Member Access Member Functions (inline, const) Object Copy C++ program= .h +.cpp. - PowerPoint PPT Presentation

Transcript of Objects and Classes in C++

Page 1: Objects and Classes in C++

1

Objects and Classes in C++

Lesson #4

Note: CIS 601 notes were originally developed by H. Zhu for NJIT DL Program. The notes were subsequently revised by M. Deek.

Page 2: Objects and Classes in C++

2

Content

Class/Object Definition Member Access Member Functions (inline, const) Object Copy C++ program= .h +.cpp

Page 3: Objects and Classes in C++

3

Classes and their instances Class ::=<Id, Ds, Ops, Intfc>; Object ::= <Oid, Cid, Body>. In C++:

class class_name{ Member_list };//Class

Member_List::=MemberVariables|MemberFunctions

class_name identifier;//Object

Page 4: Objects and Classes in C++

4

Class Definitionclass Point {

public:

int GetX(); // return the value of x

int GetY(); // return the value of y

void SetX(int valX) {x=valX;}; // set x

void SetY(int valY) {y=valY;}; //set y

private:

int x,y;//coordinates

}

Page 5: Objects and Classes in C++

5

Class Point (Member Functions)

int Point::GetX() { return x; }; int Point::GetY() { return y;

};

Page 6: Objects and Classes in C++

6

Class Members A class object contains a copy of

the data defined in the class. The functions are shared. The data are not.

5 10 x y

20 10 x y50 60 x y

Point(int, int) int getX() int getY()

P

Q

R

Point P(5,10);Point Q(20,10);Point R(50,60);

Page 7: Objects and Classes in C++

7

Point Objects

Point P, P2;

P.SetX(300);

cout << “x= ”<< P.GetX();

P2 = p;

//ex4point.cpp

Page 8: Objects and Classes in C++

8

Page 9: Objects and Classes in C++

9

Controlling Member Access

class class_name{ public: //public membersprotected: //protected members private: //private members };

Page 10: Objects and Classes in C++

10

Access RulesType of Member

Member of the Same Class

Friend Member of a Derived Class

Non-Member Function

Private

(Default)

X X

Protected X X X

Public X X X X

Page 11: Objects and Classes in C++

11

Access Rules

For public members: You can get to the member by using the

“.” operator. E.g.: p.GetX();

For the other two member types: No!

Page 12: Objects and Classes in C++

12

Point class class Point { public:

int GetX(); // return the value of xint GetY(); // return the value of y

void SetX(int valX) {x=valX;}; // set x void SetY(int valY) {y=valY;}; //set y

int y; private: int x; //coordinates}

Page 13: Objects and Classes in C++

13

Point class

main() { Point P; P.SetX(300); P.SetY(500); cout <<"P.x="<< P.GetX()<<"\n"; cout <<"P.y="<< P.y<<"\n"; }//ex4point2.cpp

Page 14: Objects and Classes in C++

14

Page 15: Objects and Classes in C++

15

Page 16: Objects and Classes in C++

16

In-line Functions

In-line: functions are defined within the body of the class definition.

Out-of-line: functions are declared within the body of the class definition and defined outside.

inline keyword: Used to defined an inline function outside the class definition.

Page 17: Objects and Classes in C++

17

class Point {

public:

void setX(int valX) {x=valX;}; // set x

void setY(int valY); //set y

void delta(int, int); //adjust the coordinators

private:

int x,y; //the coordinates

}

void Point::setY(int valY) {y=valY;}

inline void Point::delta(int dx, int dy)

{x +=dx; y+=dy;}

In-line

Out-of-line

Also In-line

Omitting the name is allowed

Page 18: Objects and Classes in C++

18

Constant Member Function Guarantees that the state of the current

class object is not modified.

class Point {

public:

int getX() const {return x;};

int getY(){return y;};

void setX(int valX) {x=valX;}; // set x

}

Page 19: Objects and Classes in C++

19

Constant Functions

const Point P1(10, 20);

Point P2(30, 50);

P1.getX();

P2.getX();//a const function can be //called by a non-const object

P1.SetX(100); //error! P1 is a const obj

P2.SetX(100); //ok

Page 20: Objects and Classes in C++

20

Constructors

Called to create an object. Default constructors: no parameters.class Point {

public:

Point() {};

// Point() {x=0; y=0;};

private:

int x,y; //coordinates

}

Default

Defined with initialization

Page 21: Objects and Classes in C++

21

Constructors

Alternate constructors: with parameters Point::Point(int vx, int vy) { setX(vx); setY(vy); cout<<“Point constructor called.\n”; }

Page 22: Objects and Classes in C++

22

Constructors

Overloading Constructors: with different parameters

Point(); Point(int, int) are overloaded constructors.

Example: ex4point3.cpp

Page 23: Objects and Classes in C++

23

Page 24: Objects and Classes in C++

24

Page 25: Objects and Classes in C++

25

Constructors

Copy constructors: default ones are created by the compiler automatically.

A local copy of the object is constructed.

Copy constructors can also be defined by the programmer.

Page 26: Objects and Classes in C++

26

Objects of a class

Point p; //default Point a(p), b = p; //copy Point c(20,30); //alternate Point figure[3]; //default Point figure[2] = {p,c}; //copy Example: ex4point4.cpp

Page 27: Objects and Classes in C++

27

Page 28: Objects and Classes in C++

28

Page 29: Objects and Classes in C++

29

Pointers to Class Objects

Student *p; p = new Student; if (!p) //could not create Student Point * figure = new Point[10]; //call Point() 10 times Delete [] figure;//7.3.3,p233

Page 30: Objects and Classes in C++

30

Destructors

Called when an object is to be deleted.

Defined with the name:~classname(); Example: Ex4point4.cpp

~Point(){cout <<“Destructor called.”;}

Page 31: Objects and Classes in C++

31

Page 32: Objects and Classes in C++

32

Page 33: Objects and Classes in C++

33

Constructors and Destructors with dynamic memory

//Vstring Class#include <string.h>#include <iostream.h>class VString {public: VString( unsigned len = 0 ); // Construct a VString of size <len>. VString( const char * s ); // Construct a VString from a C-style string.

~VString(); // Destructor

Page 34: Objects and Classes in C++

34

VStringunsigned GetSize() const; // Returns the number of characters.private: char * str; // character array unsigned size; // allocation size};VString::VString( unsigned len ){ size = len; str = new char[ size+1 ];//Dynamic str[0] = '\0';}

Page 35: Objects and Classes in C++

35

VStringVString::VString( const char * s )

{ size = strlen( s );

str = new char[ size+1 ];

strcpy( str, s );}

VString::~VString()

{ delete [] str;}

unsigned VString::GetSize() const

{ return size;}

Page 36: Objects and Classes in C++

36

VString

int main()

{VString zeroLen;

VString emptyStr( 50 );

VString aName( "John Smith" );

cout << aName.GetSize() << endl;

return 0;

}//ex4vstring.cpp

Page 37: Objects and Classes in C++

37

Page 38: Objects and Classes in C++

38

Page 39: Objects and Classes in C++

39

Copy Constructors

Makes a duplicate copy of an object of the same class. The default makes a bit-wise copy of the the object.

A copy constructor is invoked automatically when a temporary object is constructed from an existing one.

Page 40: Objects and Classes in C++

40

Student#include <iostream.h>

class Student {

public:

Student() { cout << "default constructor,"; }

Student( const Student & s ) { cout << "copy constructor,"; }

~Student() { cout << "destructor,"; }

friend ostream & operator <<( ostream & os, const Student & s )

{ cout << "Student,";

return os;}

};

Page 41: Objects and Classes in C++

41

StudentStudent InputNewStudent(){ Student aStudent;//A default constructor //... return aStudent;//A copy constructor}int main(){Student aStudent; //... return aStudent;}//ex4student.cpp

Page 42: Objects and Classes in C++

42

Page 43: Objects and Classes in C++

43

Page 44: Objects and Classes in C++

44

Deep Copy Operation Deep copy—copies the contents of an

object. char name[] = “John Smith”;

char * cp = new char[30];

strcpy(cp,name);

Shallow copy—copy the pointer of an object. char name[] = “John Smith”;

char * cp = name;

Page 45: Objects and Classes in C++

45

Student Copy#include "fstring.h"

class Course {

public:

Course( const FString & cname );

private:

FString name;

};

class Student {

public:

Student( unsigned ncourses );

~Student();

Page 46: Objects and Classes in C++

46

Student Copyprivate:

Course * coursesTaken;

unsigned numCourses;

};

Student::Student( unsigned ncourses )

{ coursesTaken = new Course[ncourses];

numCourses = ncourses;}

Student::~Student()

{ delete [] coursesTaken;}

Page 47: Objects and Classes in C++

47

Student Copy int ncourses = 7;

Student X(ncourses);

Student Y(X);

X

Y

array of course objects

X

Y

array of course objectsIf you’d like the following:

Page 48: Objects and Classes in C++

48

Student CopyClass Student {//…Public:Student(const Student & S);//…}Student:: Student(const Student & S){numcourses = S.numCourses; courseTaken = new Course[numcourses]; for (unsigned i =0; i < numcourses; i++) courseTaken[i]= S.courseTaken[I];}

Page 49: Objects and Classes in C++

49

Composite Classes

A class which contains data members that are objects of other classes.

When a class contains instances, references, or pointers to other classes, we call it a composite class.

Page 50: Objects and Classes in C++

50

Composite Classes

class Transcript{//…};

class Address{//…};

class Student {

public:

private:

long id;

Transcript tr;

Address addr;

float gradeAverage;

}

Page 51: Objects and Classes in C++

51

Composite Classes class Point { public: Point(); Point( const int xv, const int yv ); private: int x; int y; };

Page 52: Objects and Classes in C++

52

Composite Classes

const int MaxVertices = 10; enum Colors {white, blue, green} class Figure{public: Figure(); void SetCenter( const Point & P ); void SetColor( const int colr ); void SetVertex( const int n, const Point & P ); private: Point vertex[MaxVertices]; // array of vertices int vcount; // number of vertices Point center; // center of rotation int color; // color };

Page 53: Objects and Classes in C++

53

Composite Classes

int main(){Figure F;F.SetVertex( 0, Point( 1, 1 ));F.SetVertex( 1, Point( 10, 2 ));F.SetVertex( 2, Point( 8, 10 ));F.SetVertex( 3, Point( -2, 2 ));F.SetCenter(Point P( 6, 5 ) );const int FigCount = 5;Figure figList[FigCount]; // array of Figuresfor(int j = 0; j < FigCount; j++) figList[j].SetColor( green );return 0;}

Page 54: Objects and Classes in C++

54

Pre-defined Order The constructors for all member objects

are executed in the order in which they appear in the class definition. All member constructors are executed before the body of the enclosed class constructor executes.

Destructors are called in the reverse order of constructors. Therefore, the body of the enclosed class destructor is executed before the destructors of its member objects.

Page 55: Objects and Classes in C++

55

#include <iostream.h> class Point { public: Point() { cout << "Point constructor\n"; } ~Point() { cout << "Point destructor\n"; } };

Example: preorder.cpp

Page 56: Objects and Classes in C++

56

preorder.cpp const int MaxVertices = 3; class Figure { public: Figure() { cout << "Figure constructor\n"; } ~Figure() { cout << "Figure destructor\n"; } private: Point vertex[MaxVertices]; // array of vertices Point center; }; int main() { Figure F; return 0; }//ex4preorder.cpp

Page 57: Objects and Classes in C++

57

Page 58: Objects and Classes in C++

58

Page 59: Objects and Classes in C++

59

Passing messages

Data members should be private. Public data members violate the

principles of encapsulation. Function members can be public.

Page 60: Objects and Classes in C++

60

Axis class Axis { public: void SetTitle( const char * st ); void SetRange( int min, int max ); //... }; class ChartData { public: void Read( istream & inp ); //... };

Page 61: Objects and Classes in C++

61

Chart.cpp #include <iostream.h> #include <fstream.h> class Axis { public: void SetTitle( const char * st ); //... }; class ChartData { public: void Read( istream & ); //... };

Page 62: Objects and Classes in C++

62

Chart.cpp class Chart { public: Axis & HorizontalAxis() { return horizAxis; } Axis & VerticalAxis() { return verticalAxis; } ChartData & DataSet() { return dataset; } void Draw(); private: Axis horizAxis; Axis verticalAxis; ChartData dataset; };

Page 63: Objects and Classes in C++

63

Chart.cpp

int main() { Chart sales; sales.HorizontalAxis().SetTitle( "Revenue" ); sales.VerticalAxis().SetTitle( "Products" ); ifstream infile( "sales.dta" ); sales.DataSet().Read( infile ); return 0; }

Page 64: Objects and Classes in C++

64

Initializing Class Members

Constructor-initializer:class_name(argument_lis):member1(ctor_arglist1),member2

(ctor_arglist2),…{//…}

Example: enum Colors{white, blue, green};class Point { public: Point (cons Point &p); //…}

Page 65: Objects and Classes in C++

65

Class Figure{ public: Figure(const Point & ctr; Colors aClolor); //… private: Point center; Colors color; } Figure::Figure(const Point & ctr; Colors aClolor) : color(aColor),center(ctr) {color = aColor; Center = ctr; }

Initialization

Page 66: Objects and Classes in C++

66

Static Class Members

Declared as “static” Both data and function members may be

declared as static. Only one copy exists. Are controlled by the enclosing class. A static function can only access the static

members and the enumerated constants of a class.

Example: student.cpp

Page 67: Objects and Classes in C++

67

Student.cpp typedef unsigned long ulong; class Student { public: Student( ulong id ); // Construct Student from an id number. Student( const Student & S ); // Construct from another Student. ~Student(); static ulong GetCount(); // Return the static instance count. private: static ulong count; // instance count ulong idNum; // identification number };

Page 68: Objects and Classes in C++

68

Student.cpp

ulong Student::count = 0; // define, initialize Student::Student( ulong id ) { idNum = id; count++; } Student::Student( const Student & S ) { idNum = S.idNum; count++; } Student::~Student() { count--; } ulong Student::GetCount() { return count; }

Page 69: Objects and Classes in C++

69

Student.cpp #include <iostream.h> void MakeStudent() { Student C( 200001L ); cout << Student::GetCount() << endl; // displays "3" } int main() { Student A( 100001L ); cout << Student::GetCount() << endl; // displays "1" Student B( A ); cout << Student::GetCount() << endl; // displays "2" MakeStudent(); // displays "3“, then -1 cout << Student::GetCount() << endl; // displays "2" return 0; }//ex4student2.cpp

Page 70: Objects and Classes in C++

70

Page 71: Objects and Classes in C++

71

Page 72: Objects and Classes in C++

72

An example: Dive// DIVE.H - Dive class definition// Also contains in-line member functions.#include <iostream.h>class Dive {public: Dive( float avg, float diff ); float CalcTotalPoints() const; void Display() const; void SetDifficulty( float diff ); void SetJudgeScore( float score );private: float judgeScore; // average judges score float difficulty; // degree of difficulty};

Page 73: Objects and Classes in C++

73

Dive.cpp// DIVE.CPP - Dive class implementation.

#include "dive.h"

Dive::Dive( float avg, float diff ) // Constructor.

{ SetJudgeScore( avg );

SetDifficulty( diff );

}

void Dive::Display() const

{// Display the Dive on the console.

cout << "[Dive]: "

<< judgeScore << ','

<< difficulty << ','

<< CalcTotalPoints()

<< endl;

}

Page 74: Objects and Classes in C++

74

Dive.cppvoid Dive::SetDifficulty( float diff ){ if((diff >= 1.0) && (diff <= 5.0)) difficulty = diff; else cerr << "Range error in Dive::SetDifficulty()" << " value: " << diff << endl;}void Dive::SetJudgeScore( float score ){ judgeScore = score;}float Dive::CalcTotalPoints() const{ return judgeScore * difficulty;}

Page 75: Objects and Classes in C++

75

Main.cpp#include "dive.h"int main(){ Dive D1( 8.5, 3.0 ); // create 3 dives Dive D2( 9.0, 2.5 ); Dive D3( 8.0, 3.3 ); D1.Display(); // display 3 dives D2.Display(); D3.Display(); D2.SetDifficulty( 3.0 ); // modify difficulty // Display the Dives again. cout << "\nChanging Dive 2\n"; D1.Display(); D2.Display(); D3.Display(); return 0;}ex4dive.cpp

Page 76: Objects and Classes in C++

76

Page 77: Objects and Classes in C++

77

Page 78: Objects and Classes in C++

78

Text File Streams //…Reading ifstream infile(“payroll.dat”); if (!infile) cerr <<“Error:open file.\n”; else { infile >> employeeId >> hoursWorked >> payRate; //… }

Page 79: Objects and Classes in C++

79

Text File Streams

infile.close() //close the file infile.open(“payroll.dat”, ios::in); //open while (!infile.eof()) //check the end of file { infile >>employeeId>>hoursWorked>>

payRate; //… }

Page 80: Objects and Classes in C++

80

Text File Streams

recLen = 10;

recNum = 3;

offset = (recNum -1) * recLen;

infile.seeg(offset, ios::beg);

char buf[10];

infile.get(buf, 10);

cout<<buf<<endl;

Page 81: Objects and Classes in C++

81

Text File Streams

ios::beg //from the beginning ios::end //from the end ios::cur //from the current position infile.seekg(-10, ios::end); infile.seekg(-1, ios::cur); streampos p = infile.tellg(); //current position

Page 82: Objects and Classes in C++

82

Text File Streams ofstream ofile(“payroll.dat”, ios::out); … if (!ofile) cerr<<“Error:open file.\n”; else{ ofile << employeeId<<hoursWorked << payRate <<endl;} ofile.open(“payroll.dat”, ios::out); //new for out ofile.open(“payroll.dat”, ios::app); //append

Page 83: Objects and Classes in C++

83

Example: Student Registration

Sample data for a student:102234 //student ID

962 //semester (96/2)

CHM_1020 C 3//Section C, 3 credits

MUS_1100 H 1//Section H, 1 credits

BIO_1040 D 4 //Section D, 4 credits

MTH_2400 A 3 //Section A, 3 credits

Page 84: Objects and Classes in C++

84

Course.h #include <iostream.h> #include <fstream.h> const unsigned CnameSize = 10; class Course { public: Course(); void Input( ifstream & infile ); void Output( ofstream & ofile ) const; private: char name[CnameSize]; // course name char section; // section (letter) unsigned credits; // number of credits };

Page 85: Objects and Classes in C++

85

Course.h

const unsigned MaxCourses = 10; class Registration { public: Registration(); void Input( ifstream & infile ); void Output( ofstream & ofile ) const; private: long studentId; // student ID number unsigned semester; // semester year, number unsigned count; // number of courses Course courses[MaxCourses]; // array of courses };

Page 86: Objects and Classes in C++

86

Regist.cpp #include "course.h" Course::Course() { name[0] = '\0';} void Course::Input( ifstream & infile ) { infile >> name >> section >> credits;} void Course::Output( ofstream & ofile ) const { ofile << " Course: " << name << '\n' << " Section: " << section << '\n' << " Credits: " << credits << endl; } Registration::Registration() { count = 0;}

Page 87: Objects and Classes in C++

87

Regist.cpp

void Registration::Input( ifstream & infile ) { infile >> studentId >> semester >> count; for(int i = 0; i < count; i++) courses[i].Input( infile ); } void Registration::Output( ofstream & ofile ) const { ofile << "Student ID: " << studentId << '\n' << "Semester: " << semester << '\n'; for(int i = 0; i < count; i++) { courses[i].Output( ofile ); ofile << '\n'; } }

Page 88: Objects and Classes in C++

88

Main.cpp #include "course.h" int main() { // Read a Registration object from an input // file and write it to an output file. ifstream infile( "rinput.txt" ); if( !infile ) return -1; Registration R; R.Input( infile ); ofstream ofile( "routput.txt", ios::app ); if( !ofile ) return -1; R.Output( ofile ); return 0; }

Page 89: Objects and Classes in C++

89

Page 90: Objects and Classes in C++

90

Page 91: Objects and Classes in C++

91

Page 92: Objects and Classes in C++

92

Readings

Readings Chapter 2 Sections 2.2 - 2.7, Chapter 4, Chapter 7 Section 7.5