tailieunhanh - Object Oriented Programming (20)

CSC241: Object Oriented Programming. Lecture No 22. 1 Previous Lecture.•. Friend function. – example program: Distance class. – Friend function for functional notation.•. Friend classes.•. static functions.•. Assignment operator and copy initialization. 2 Today’s Lecture.•. Example program. – Copy initialization. – Assignment operator overloaded.•. Memory efficient string class.•. Dynamic Type Information. 3 The Copy Constructor.•. Distance d2 = d1;. d2 d1. feet 7 feet 7. inche inche. . s s•. It is similar to what assignment operator (d2 =. d1) does.•. The difference is that copy initialization also. creates a new object 4 Example program – assignment alpha { copy constructor. void display(). private: { cout << data; }. int data; void operator = (alpha&. public: a) {. alpha() { } data = ;. alpha(int d) cout << “\nAssignment. { data = d; } operator invoked”;. alpha(alpha& a) { }. data = ; };. cout << “\nCopy a2 = a1;. alpha a3(a1);. constructor. invoked”; Program Output. } Assignment operator. invoked. Copy constructor invoked. 5 When Copy constructor is invoked1. Copy constructor may be invoked when an. object is defined. . alpha a3 = a2; or alpha a3(a2);.2. when arguments are passed by value to. functions void func(alpha a) { . . . }Alpha a =. called by the statement a1;. func(a1);.5. when values are returned from functions. 6 Why Not alpha(alpha a) Constructor?.•. Do we need to use a reference in the argument. to the copy constructor? alpha(alpha &a).•. Could we pass by value instead? alpha(alpha a). No, the compiler complains that it is out of. memory if we try to compile.•. Why?. •. Because when an argument is passed by. value, a copy of it is constructed What makes. the copy?. •. The copy constructor. But this is the copy 7 A Memory-Efficient String Class.•. Defects with the String Class S1. This is a long. – String object contains an array of char string in. memory. – s2 = s1;. S2. – problem with this is that the same string This is a long. now exists in two (or more) places in string in. memory. memory.•. An efficient approach S1 S2. • String object contain its own char*. • s2 = s1; This is a long. string in. • This is efficient, since only a single copy memory. of the string itself needs to be stored in 8 Problem with efficient approach.•. If we use this system we need to be careful. when we destroy a String object.•. Consider a situation in which several objects are. point to same string. S1 S2 S3.•. If one string objec

TỪ KHÓA LIÊN QUAN
crossorigin="anonymous">
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.