Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.

Similar presentations


Presentation on theme: "1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings."— Presentation transcript:

1

2 1 Classes II Chapter 7

3 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings –helps to understand pointers –lots still around from old C code

4 3 const Objects General concept … objects should not be modifiable unless necessary –shows up in use of private variables, public access functions –called "principle of least privilege" Also shows up in use of declaring objects as const –attempts to modify object caught at compile time –no execution time errors

5 4 const Objects Declaring objects as const can also improve performance –optimizing compilers can make the code quicker with constants –not possible with variables

6 5 const Member Functions Function can be specified as const –such functions cannot modify the object –compiler disallows Note : such a function must not call a non- const member function Also : constructors cannot be const since they must initialize values int Time::getTime() const ;

7 6 const Member Functions If you declare a const object –you must initialize it in the declaration –it cannot be given a value otherwise Note fig 7.1.5, pg 422 combination of –non- const member functions with const objects –const member functions with non- const objects Always declare member functions as const if they don't modify an object

8 7 Composition:Objects as Members of Classes A class can have objects of other classes as members This is a form of reusability Examples … –an Employee class might use objects of type Date –an Alarmclock class might use an object of type Time –a CheckingAccount class might use an object of type BankAccount Note Figure 7.4 pgs 427 - 431

9 8 Composition:Objects as Members of Classes Note constructors with default values –line 9, figure 7.4 Note use of const private members –lines 96,97 Initialize member objects explicitly through member initializers –Note lines 111 & 112 Destructors used in example to show when they got implicitly called

10 9 Parameters of class Type Consider a public function of a class that must reference another instance of the same class Call to that function by client x = c1.whatever (c2); –note that this is somewhat awkward class c_type { public : int whatever (c_type c);... };

11 10 Motivation for friend Function Would be nice to have a more natural call to the function Problem: –would possibly be accessing private data members of two separate instances of a class Solution -- friend function is given permission to access private data of another class or instance of a class x = whatever (c1, c2);

12 11 friend Functions and Classes Defined outside the class's scope But … has the right to access private members of the class Appropriate when a member function cannot be used for certain operations Used extensively for "overloading" operators

13 12 friend Functions and Classes Declaring a friend function –precede the prototype with keyword friend –shown here before private and public but can be anywhere in the class definition –note that friend functions appear inside the class defninitions But … they are not members of the class class Count { friend void setX( Count &, int ); // friend declaration public: Count() { x = 0; } // constructor void print() const { cout << x << endl; } // output private: int x; // data member };

14 13 Using the this Pointer Every object has access to its own address through a pointer called this Used to implicitly reference both the data members and member functions of an object Can be used explicitly Type of the pointer depends on type of the object

15 14 Using the this Pointer class Test{ public: Test( int = 0); void print () const; private:int x; } ; Test::Test (int a) x = a; } // constructor void Test::print() const { cout x = " x << endl; cout << "(*this).x ="<< (*this).x; } class Test{ public: Test( int = 0); void print () const; private:int x; } ; Test::Test (int a) x = a; } // constructor void Test::print() const { cout x = " x << endl; cout << "(*this).x ="<< (*this).x; } Note use of arrow operator Note use of. dot operator of dereferenced pointer

16 15 Using the this Pointer Note use of functions which return * this Type of value return by the functions is reference or address Then calls to functions for single object can be "cascaded" t.setHour(15).setMinute(37).setSecond(45); dot operator. associates L to R

17 16 Dynamic Memory Allocation Operators provided for allocation of memory of a certain size at run time new operator –creates an object of proper size –calls constructor for the object –returns a pointer of the correct type bankAcctPtr = new BankAccount;

18 17 Dynamic Memory Allocation If new is unable to find space, it returns a 0 pointer To free space for this object use delete command –automatically invokes the class's destructor Note, C used malloc and free –best not to mix these in same program –they are not interchangeable

19 18 Dynamic Memory Allocation Possible to initialize object created with new Create array with new delete the array float *amtPtr = new float (2.7159); int * listPtr = new int [20]; delete [] listPtr;

20 19 static Class Members Consider multiple instantiations of a class Each individual object has –a common copy of member function code –its own copy of the data members Occasionally we wish to have one of the data members common to all objects in existence –otherwise must have a way to update that data member separately for each object

21 20 static Class Members To have one common data member for all objects of a class type –specify that class variable as static Saves space for redundant copies of the variable Saves time in updating the class-wide data element … private: char *name; static int counter; };

22 21 Data Abstraction, Information Hiding Classes normally hide their implementation details from the clients of the classes –Called "information hiding" User (programmer) knows only what a class does, NOT how it is implemented That way, the programmer does not write code dependent on how something is done

23 22 Data Abstraction, Information Hiding Example : Abstract Data Type (ADT) called a "stack" –Last In, First Out (LIFO) Can be implemented with an array –but programmer should NOT depend on that being the case –there are other ways to implement a stack (dynamic memory allocation) –if another implementation is used, then the code will be wrong

24 23 Abstract Data Types Abstract Data Type covers two concepts –data representation –operations allowed on that data Even built in data types provided with programming languages are only approximations or models of real-world concepts –int, float, char –addition, subtraction, multiplication, etc.

25 24 Array Abstract Data Type Capabilities built into the language for arrays are quite primitive Could use some other operations –range checking –subscripts starting with value != 0 –assignment, comparison, I/O Classes can be created to accomplish these capabilities

26 25 String Abstract Data Type Would have been possible to provide string capabilities to the C/C++ language Instead language was designed to include mechanisms for creating and implementing other abstract data types such as string Then provide things like –assignment, comparison, concatenation

27 26 Queue Abstraction Type Queue is First In, First Out (FIFO) Queue ADT hides internal data representation Offers programmer operations –enqueu => put something at end of queue –dequeue => take something off front of queue Programmer/client unaware of how queue class accomplishes these tasks

28 27 Container Classes and Iterators A type of class also known as a collection class –Holds collections of objects Provide operations such as insertion, deletion, searching, sorting, Examples: –arrays, stacks, queues, trees, linked lists Iterator : an object that returns/modifies the next item of the collection –often written as friend functions

29 28 Proxy Classes Often need to hide implementation details of a class to prevent access to proprietary information and logic Use a proxy class –knows only public interface to proprietary class

30 29 Proxy Classes Note creation of proxy class in Fig 7.10 class Implementation has the private variable value which is to be hidden Proxy class Interface shows only private *ptr to Implementation and forward declaration of Implementation Client programmer given only.cpp file for Interface and.obj files for Implementation


Download ppt "1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings."

Similar presentations


Ads by Google