Download presentation
Presentation is loading. Please wait.
1
Value Semantics CS-240 & CS-341 Dick Steflik
2
Value Semantics determine how the value(s) of one object are copied to another object in C++ the value semantics consist of the assignment operator and the copy constructor these allow assignment of one object to another and the creation of one object from another
3
for simple/static objects the default assignment operator and copy constructor will do what is needed; i.e. a member by member copy of the elements making up the object. class Date { public: Date(int m,int d, int y) private: int month,day,year } Date today(5,5,2000); Date May5(today); /* create May5 from today, default copy constructor */ Date May5th ; May5th = today; /* create an object called May5th then assign it a value, default assignment operator*/
4
for dynamic objects where the private data includes dynamically allocated data (ex. dynamic array) we must overload both the default copy constructor and the default assignment operator. class Stack{ public: Stack(); Stack (int size); Stack (const Stack & source); void operator = (const & source); private: int * data; int top; }
5
implementation Stack::Stack() /* default constructor */ { data = new int[10]; top = 0; } Stack::Stack(int size) /* constructor */ { data = new int[size]; top = 0; }
6
copy constructor create the object with the correct size, then copy the elements... Stack::Stack(const Stack & source) { int size = sizeof(source.data)/sizeof(int); /* calc the size */ data = new int[size]; /* allocate */ for (int i = 0 ; i < size; i++) /* copy the data */ data[i] = source[i]; top = source.top; /* copy the top pointer */ }
7
overload assignment operator calculate the size, discard the old data store, make a new one, then copy elements over... void Stack::operator = (const Stack * source) { int size = sizeof(source.data)/sizeof(int); delete data; data = new int[size]; for (int i=0 ; i< size ; i++) data[i] = source.data[i]; top = source.top; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.