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.

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

Embed Size (px)

Citation preview

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.

2

Content

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

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

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

}

5

Class Point (Member Functions)

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

};

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

7

Point Objects

Point P, P2;

P.SetX(300);

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

P2 = p;

//ex4point.cpp

8

9

Controlling Member Access

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

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

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!

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}

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

14

15

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.

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

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

}

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

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

21

Constructors

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

22

Constructors

Overloading Constructors: with different parameters

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

Example: ex4point3.cpp

23

24

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.

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

27

28

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

30

Destructors

Called when an object is to be deleted.

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

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

31

32

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

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

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

36

VString

int main()

{VString zeroLen;

VString emptyStr( 50 );

VString aName( "John Smith" );

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

return 0;

}//ex4vstring.cpp

37

38

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.

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

};

41

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

42

43

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;

45

Student Copy#include "fstring.h"

class Course {

public:

Course( const FString & cname );

private:

FString name;

};

class Student {

public:

Student( unsigned ncourses );

~Student();

46

Student Copyprivate:

Course * coursesTaken;

unsigned numCourses;

};

Student::Student( unsigned ncourses )

{ coursesTaken = new Course[ncourses];

numCourses = ncourses;}

Student::~Student()

{ delete [] coursesTaken;}

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:

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

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.

50

Composite Classes

class Transcript{//…};

class Address{//…};

class Student {

public:

private:

long id;

Transcript tr;

Address addr;

float gradeAverage;

}

51

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

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

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

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.

55

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

Example: preorder.cpp

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

57

58

59

Passing messages

Data members should be private. Public data members violate the

principles of encapsulation. Function members can be public.

60

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

61

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

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

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

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); //…}

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

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

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

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

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

70

71

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

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;

}

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

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

76

77

78

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

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

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;

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

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

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

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

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

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

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

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

89

90

91

92

Readings

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