Download presentation
Presentation is loading. Please wait.
Published byCamilla Joseph Modified over 10 years ago
1
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
2 Content u Class/Object Definition u Member Access u Member Functions (inline, const) u Object Copy u C++ program=.h +.cpp
3
3 Classes and their instances u Class ::= ; u Object ::=. u In C++: u class class_name{ Member_list };//Class Member_List::=MemberVariables|MemberFun ctions u class_name identifier;//Object
4
4 Class Definition class 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
5 Class Point (Member Functions) u int Point::GetX() u { u return x; u }; u int Point::GetY() u { u return y; u };
6
6 Class Members u A class object contains a copy of the data defined in the class. u The functions are shared. u The data are not. 5 10 x y 20 10 x y 50 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
7 Point Objects Point P, P2; P.SetX(300); cout << “x= ”<< P.GetX(); P2 = p; //ex4point.cpp
8
8
9
9 Controlling Member Access class class_name{ public: //public members protected: //protected members private: //private members };
10
10 Access Rules Type of Member Member of the Same Class FriendMember of a Derived Class Non- Member Function Private (Default) XX ProtectedXXX PublicXXXX
11
11 Access Rules u For public members: u You can get to the member by using the “.” operator. u E.g.: p.GetX(); u For the other two member types: u No!
12
12 Point class class 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 int y; private: int x;//coordinates }
13
13 Point class u main() u { u Point P; u P.SetX(300); u P.SetY(500); u cout <<"P.x="<< P.GetX()<<"\n"; u cout <<"P.y="<< P.y<<"\n"; u }//ex4point2.cpp
14
14
15
15
16
16 In-line Functions u In-line: functions are defined within the body of the class definition. u Out-of-line: functions are declared within the body of the class definition and defined outside. u inline keyword: Used to defined an inline function outside the class definition.
17
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
18 Constant Member Function u 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
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
20 Constructors u Called to create an object. u Default constructors: no parameters. class Point { public: Point() {}; // Point() {x=0; y=0;}; … private: int x,y;//coordinates } Default Defined with initialization
21
21 Constructors u Alternate constructors: with parameters u Point::Point(int vx, int vy) u { setX(vx); u setY(vy); u cout<<“Point constructor called.\n”; u }
22
22 Constructors u Overloading Constructors: with different parameters u Point(); Point(int, int) are overloaded constructors. u Example: ex4point3.cpp
23
23
24
24
25
25 Constructors u Copy constructors: default ones are created by the compiler automatically. u A local copy of the object is constructed. u Copy constructors can also be defined by the programmer.
26
26 Objects of a class u Point p;//default u Point a(p), b = p;//copy u Point c(20,30);//alternate u Point figure[3];//default u Point figure[2] = {p,c};//copy u Example: ex4point4.cpp
27
27
28
28
29
29 Pointers to Class Objects u Student *p; u p = new Student; u if (!p) //could not create Student u Point * figure = new Point[10]; u //call Point() 10 times u Delete [] figure;//7.3.3,p233
30
30 Destructors u Called when an object is to be deleted. u Defined with the name:~classname(); u Example: Ex4point4.cpp u ~Point(){cout <<“Destructor called.”;}
31
31
32
32
33
33 Constructors and Destructors with dynamic memory //Vstring Class #include class VString { public: VString( unsigned len = 0 ); // Construct a VString of size. VString( const char * s ); // Construct a VString from a C-style string. ~VString(); // Destructor
34
34 VString unsigned 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
35 VString VString::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
36 VString int main() {VString zeroLen; VString emptyStr( 50 ); VString aName( "John Smith" ); cout << aName.GetSize() << endl; return 0; }//ex4vstring.cpp
37
37
38
38
39
39 Copy Constructors u Makes a duplicate copy of an object of the same class. The default makes a bit-wise copy of the the object. u A copy constructor is invoked automatically when a temporary object is constructed from an existing one.
40
40 Student #include 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
41 Student Student InputNewStudent() { Student aStudent;//A default constructor //... return aStudent;//A copy constructor } int main() {Student aStudent; //... return aStudent; }//ex4student.cpp
42
42
43
43
44
44 Deep Copy Operation u Deep copy—copies the contents of an object. char name[] = “John Smith”; char * cp = new char[30]; strcpy(cp,name); u Shallow copy—copy the pointer of an object. char name[] = “John Smith”; char * cp = name;
45
45 Student Copy #include "fstring.h" class Course { public: Course( const FString & cname ); private: FString name; }; class Student { public: Student( unsigned ncourses ); ~Student();
46
46 Student Copy private: Course * coursesTaken; unsigned numCourses; }; Student::Student( unsigned ncourses ) { coursesTaken = new Course[ncourses]; numCourses = ncourses;} Student::~Student() { delete [] coursesTaken;}
47
47 Student Copy int ncourses = 7; Student X(ncourses); Student Y(X); X Y array of course objects X Y If you’d like the following:
48
48 Student Copy Class 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
49 Composite Classes u A class which contains data members that are objects of other classes. u When a class contains instances, references, or pointers to other classes, we call it a composite class.
50
50 Composite Classes u class Transcript{//…}; u class Address{//…}; u class Student { u public: u … u private: long id; Transcript tr; Address addr; float gradeAverage; }
51
51 Composite Classes u class Point u { u public: u Point(); u Point( const int xv, const int yv ); u private: u int x; u int y; u };
52
52 Composite Classes u const int MaxVertices = 10; u enum Colors {white, blue, green} u class Figure{public: u Figure(); u void SetCenter( const Point & P ); u void SetColor( const int colr ); u void SetVertex( const int n, const Point & P ); u private: u Point vertex[MaxVertices]; // array of vertices u int vcount; // number of vertices u Point center; // center of rotation u int color; // color u };
53
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 Figures for(int j = 0; j < FigCount; j++) figList[j].SetColor( green ); return 0; }
54
54 Pre-defined Order u 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. u 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
55 u #include u class Point { u public: u Point() { cout << "Point constructor\n"; } u ~Point() { cout << "Point destructor\n"; } u }; Example: preorder.cpp
56
56 preorder.cpp u const int MaxVertices = 3; u class Figure { u public: u Figure() { cout << "Figure constructor\n"; } u ~Figure() { cout << "Figure destructor\n"; } u private: u Point vertex[MaxVertices]; // array of vertices u Point center; u }; u int main() u { u Figure F; u return 0; u }//ex4preorder.cpp
57
57
58
58
59
59 Passing messages u Data members should be private. u Public data members violate the principles of encapsulation. u Function members can be public.
60
60 Axis u class Axis { u public: u void SetTitle( const char * st ); u void SetRange( int min, int max ); u //... u }; u class ChartData { u public: u void Read( istream & inp ); u //... u };
61
61 Chart.cpp u #include u class Axis { u public: u void SetTitle( const char * st ); u //... u }; u class ChartData { u public: u void Read( istream & ); u //... u };
62
62 Chart.cpp u class Chart { u public: u Axis & HorizontalAxis() { return horizAxis; } u Axis & VerticalAxis() { return verticalAxis; } u ChartData & DataSet() { return dataset; } u void Draw(); u private: u Axis horizAxis; u Axis verticalAxis; u ChartData dataset; u };
63
63 Chart.cpp u int main() u { u Chart sales; u sales.HorizontalAxis().SetTitle( "Revenue" ); u sales.VerticalAxis().SetTitle( "Products" ); u ifstream infile( "sales.dta" ); u sales.DataSet().Read( infile ); u return 0; u }
64
64 Initializing Class Members u Constructor-initializer: class_name(argument_lis):member1(ctor_arglist1),member2( ctor_arglist2),… {//… } u Example: enum Colors{white, blue, green}; class Point { public: Point (cons Point &p); //… }
65
65 u Class Figure{ u public: u Figure(const Point & ctr; Colors aClolor); u //… u private: u Point center; u Colors color; u } u Figure::Figure(const Point & ctr; Colors aClolor) u : color(aColor),center(ctr) u {color = aColor; u Center = ctr; u } Initialization
66
66 Static Class Members u Declared as “static” u Both data and function members may be declared as static. u Only one copy exists. u Are controlled by the enclosing class. u A static function can only access the static members and the enumerated constants of a class. u Example: student.cpp
67
67 Student.cpp u typedef unsigned long ulong; u class Student { u public: u Student( ulong id ); u // Construct Student from an id number. u Student( const Student & S ); u // Construct from another Student. u ~Student(); u static ulong GetCount(); u // Return the static instance count. u private: u static ulong count; // instance count u ulong idNum; // identification number u };
68
68 Student.cpp u ulong Student::count = 0; // define, initialize u Student::Student( ulong id ) u { idNum = id; u count++; u } u Student::Student( const Student & S ) u { idNum = S.idNum; u count++; u } u Student::~Student() u { count--; u } u ulong Student::GetCount() u { return count; u }
69
69 Student.cpp u #include u void MakeStudent() u { u Student C( 200001L ); u cout << Student::GetCount() << endl; // displays "3" u } u int main() u { u Student A( 100001L ); u cout << Student::GetCount() << endl; // displays "1" u Student B( A ); u cout << Student::GetCount() << endl; // displays "2" u MakeStudent(); // displays "3“, then -1 u cout << Student::GetCount() << endl; // displays "2" u return 0; u }//ex4student2.cpp
70
70
71
71
72
72 An example: Dive // DIVE.H - Dive class definition // Also contains in-line member functions. #include 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
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
74 Dive.cpp void 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
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
76
77
77
78
78 Text File Streams //…Reading ifstream infile(“payroll.dat”); if (!infile) cerr <<“Error:open file.\n”; else { infile >> employeeId >> hoursWorked >> payRate; //… }
79
79 Text File Streams u infile.close() //close the file u infile.open(“payroll.dat”, ios::in); //open u while (!infile.eof()) //check the end of file u { infile >>employeeId>>hoursWorked>> payRate; u //… u }
80
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
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
82 Text File Streams ofstream ofile(“payroll.dat”, ios::out); … if (!ofile) cerr<<“Error:open file.\n”; else { ofile << employeeId<<hoursWorked << payRate <<endl; } u ofile.open(“payroll.dat”, ios::out); //new for out u ofile.open(“payroll.dat”, ios::app); //append
83
83 Example: Student Registration u 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
84 Course.h u #include u const unsigned CnameSize = 10; u class Course { u public: u Course(); u void Input( ifstream & infile ); u void Output( ofstream & ofile ) const; u private: u char name[CnameSize]; // course name u char section; // section (letter) u unsigned credits; // number of credits u };
85
85 Course.h u const unsigned MaxCourses = 10; u class Registration { u public: u Registration(); u void Input( ifstream & infile ); u void Output( ofstream & ofile ) const; u private: u long studentId; // student ID number u unsigned semester; // semester year, number u unsigned count; // number of courses u Course courses[MaxCourses]; // array of courses u };
86
86 Regist.cpp u #include "course.h" u Course::Course() u { name[0] = '\0';} u void Course::Input( ifstream & infile ) u { infile >> name >> section >> credits;} u void Course::Output( ofstream & ofile ) const u { ofile << " Course: " << name << '\n' u << " Section: " << section << '\n' u << " Credits: " << credits << endl; u } u Registration::Registration() u { count = 0;}
87
87 Regist.cpp u void Registration::Input( ifstream & infile ) u { infile >> studentId >> semester >> count; u for(int i = 0; i < count; i++) u courses[i].Input( infile ); u } u void Registration::Output( ofstream & ofile ) const u { ofile << "Student ID: " << studentId << '\n' u << "Semester: " << semester << '\n'; u for(int i = 0; i < count; i++) u { u courses[i].Output( ofile ); u ofile << '\n'; u }
88
88 Main.cpp u #include "course.h" u int main() u { // Read a Registration object from an input u // file and write it to an output file. u ifstream infile( "rinput.txt" ); u if( !infile ) return -1; u Registration R; u R.Input( infile ); u ofstream ofile( "routput.txt", ios::app ); u if( !ofile ) return -1; u R.Output( ofile ); u return 0; u }
89
89
90
90
91
91
92
92 Readings u Readings u Chapter 2 Sections 2.2 - 2.7, u Chapter 4, u Chapter 7 Section 7.5
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.