1 / 92

Objects and Classes in C++

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.

zeki
Download Presentation

Objects and Classes in C++

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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 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. Class Point (Member Functions) • int Point::GetX() • { • return x; • }; • int Point::GetY() • { • return y; • };

  6. 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

  7. Point Objects Point P, P2; P.SetX(300); cout << “x= ”<< P.GetX(); P2 = p; //ex4point.cpp

  8. Controlling Member Access class class_name{ public: //public members protected: //protected members private: //private members };

  9. Access Rules

  10. 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!

  11. 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 }

  12. 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

  13. 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.

  14. 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

  15. 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 … }

  16. 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

  17. 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

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

  19. Constructors • Overloading Constructors: with different parameters • Point(); Point(int, int) are overloaded constructors. • Example: ex4point3.cpp

  20. 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.

  21. 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

  22. 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

  23. Destructors • Called when an object is to be deleted. • Defined with the name:~classname(); • Example: Ex4point4.cpp • ~Point(){cout <<“Destructor called.”;}

  24. 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

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

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

  27. VString int main() {VString zeroLen; VString emptyStr( 50 ); VString aName( "John Smith" ); cout << aName.GetSize() << endl; return 0; }//ex4vstring.cpp

  28. 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.

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

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

  31. 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;

  32. Student Copy #include "fstring.h" class Course { public: Course( const FString & cname ); private: FString name; }; class Student { public: Student( unsigned ncourses ); ~Student();

  33. Student Copy private: Course * coursesTaken; unsigned numCourses; }; Student::Student( unsigned ncourses ) { coursesTaken = new Course[ncourses]; numCourses = ncourses;} Student::~Student() { delete [] coursesTaken;}

  34. 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

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

  36. 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.

  37. Composite Classes • class Transcript{//…}; • class Address{//…}; • class Student { • public: • … • private: long id; Transcript tr; Address addr; float gradeAverage; }

More Related