960 likes | 1.38k Views
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.
E N D
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
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
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 }
Class Point (Member Functions) • int Point::GetX() • { • return x; • }; • int Point::GetY() • { • return y; • };
x y x y x y 5 10 20 10 50 60 Class Members • A class object contains a copy of the data defined in the class. • The functions are shared. • The data are not. Point P(5,10); Point Q(20,10); Point R(50,60); P Point(int, int) int getX() int getY() Q R
Point Objects Point P, P2; P.SetX(300); cout << “x= ”<< P.GetX(); P2 = p; //ex4point.cpp
Controlling Member Access class class_name{ public: //public members protected: //protected members private: //private members };
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!
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 }
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
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.
Omitting the name is allowed In-line 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;} Out-of-line Also In-line
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 … }
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
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
Constructors • Alternate constructors: with parameters • Point::Point(int vx, int vy) • { setX(vx); • setY(vy); • cout<<“Point constructor called.\n”; • }
Constructors • Overloading Constructors: with different parameters • Point(); Point(int, int) are overloaded constructors. • Example: ex4point3.cpp
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.
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
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
Destructors • Called when an object is to be deleted. • Defined with the name:~classname(); • Example: Ex4point4.cpp • ~Point(){cout <<“Destructor called.”;}
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
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';}
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;}
VString int main() {VString zeroLen; VString emptyStr( 50 ); VString aName( "John Smith" ); cout << aName.GetSize() << endl; return 0; }//ex4vstring.cpp
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.
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;} };
Student Student InputNewStudent() { Student aStudent;//A default constructor //... return aStudent;//A copy constructor } int main() {Student aStudent; //... return aStudent; }//ex4student.cpp
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;
Student Copy #include "fstring.h" class Course { public: Course( const FString & cname ); private: FString name; }; class Student { public: Student( unsigned ncourses ); ~Student();
Student Copy private: Course * coursesTaken; unsigned numCourses; }; Student::Student( unsigned ncourses ) { coursesTaken = new Course[ncourses]; numCourses = ncourses;} Student::~Student() { delete [] coursesTaken;}
Student Copy int ncourses = 7; Student X(ncourses); Student Y(X); array of course objects X Y If you’d like the following: array of course objects X Y
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]; }
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.
Composite Classes • class Transcript{//…}; • class Address{//…}; • class Student { • public: • … • private: long id; Transcript tr; Address addr; float gradeAverage; }