1 / 30

CS225: Data Structures and Software Principles

CS225: Data Structures and Software Principles. More on C++. Agenda. Reference variables Parameter passing techniques const correctness Overloading Big three law Code review : intArray, string class. References. Reference : a synonym to an object

yvon
Download Presentation

CS225: Data Structures and Software Principles

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. CS225: Data Structures and Software Principles More on C++

  2. Agenda • Reference variables • Parameter passing techniques • const correctness • Overloading • Big three law • Code review : intArray, string class CS225 Spring 2005

  3. References • Reference : a synonym to an object (treat them syntactically like objects) • Be aware: • No pointers to references • No array of references • No references to references • No “constant” references (they are by default constant) int x = 5; int& x_reference = x; CS225 Spring 2005

  4. More on ReferencesCannot change what a reference refers to int i = 10; int& j = i; //j is now a reference to I j += i; //what are the values of j,i? int* k = new int(); *k = 5; j = k; //is this correct? j = *k; //is this correct? *k = 2; cout<<j<<endl; CS225 Spring 2005

  5. More on References CS225 Spring 2005

  6. Parameter passing – by value #include <iostream.h> void swap (int a, int b) { int temp = a; a = b; b = temp; } main() { int x = 1, y = 2; swap (x, y); cout << x << “ “ << y << endl; } This is semantically INCORRECT. The swap is never reflected outside the swap function because x and y are not affected at all. Only a and b are affected, and just inside swap, a is a copy of x and b is a copy of y. CS225 Spring 2005

  7. Parameter passing - pointers #include <iostream.h> void swap (int *ap, int *bp) { int temp = *ap; *ap = *bp; *bp = temp; } main() { int x = 1, y = 2; swap (&x, &y); cout << x << “ “ << y << endl; } This is semantically CORRECT. The swap is reflected outside the swap function because a copy of the pointers to x and y were passed. Any changes made to the pointer copies will not be reflected outside swap, but the changes made to the memory contents will be. CS225 Spring 2005

  8. Parameter passing – by reference #include <iostream.h> void swap (int& renamed_x, int& renamed_y) { int temp = renamed_x; renamed_x = renamed_y; renamed_y = temp; } main() { int x = 1, y = 2; swap (x, y); cout << x << “ “ << y << endl; } This is semantically CORRECT. The x of main is just renamed as renamed_x. Similarly for y. So, changes inside swap are made to the memory locations which have just been renamed. The content of renamed_x == content of x. CS225 Spring 2005

  9. Return by value #include <iostream.h> int glob; int f () { return glob; } main() { glob = 5; cout << f() << endl; } f() returns the value of glob. CS225 Spring 2005

  10. Return by pointer #include <iostream.h> int glob; int* f () { return &glob; } main() { glob = 5; cout << *(f()) << endl; } f() returns the address of glob. CS225 Spring 2005

  11. Return by pointer #include <iostream.h> int* f () { int loc = 5; return &loc; } main() { cout << *f() << endl; } BAD! loc is a variable local to f – from stack memory. Once f is done, the loc is no longer on stack and the memory where it was stored may now have a value modified by some other program. This probabilistic behavior will make it difficult to trace the bug. Code review may help! CS225 Spring 2005

  12. Return by reference #include <iostream.h> int glob; int& f () { return glob; } main() { glob = 5; f() = 10; cout << f() << endl; } The function call to f becomes the new name for the memory location of glob. For this reason, accessing contents of the location is done the same way as when accessing using the variable name. CS225 Spring 2005

  13. const keyword • Means value cannot change • Constant “variable” • const float pi = 3.14158; • float const pi = 3.14158; • Constant parameter • int compare_quotes(const Quote& quote); • Class member function • bool animal::leg_count() const; • leg_count cannot change any member variable of animal because the object cannot change inside leg_count. CS225 Spring 2005

  14. const keyword & pointers • T* ptr; A pointer to an object of type T; this is a rw pointer to a rw object • T const * ptr; A pointer to a constant T object; rw pointer to a r-only object • T * const ptr; A constant pointer to a T object; r-only pointer to a rw object • const T const* ptr; A constant pointer to a constant T object; r-only pointer to a r-only object CS225 Spring 2005

  15. Const keyword & references • References to constant objects are legal const int & intReference = x; (x may be a non –constant integer) • There is no such thing as constant references to objects • Const return type prevents changing the returned reference CS225 Spring 2005

  16. const keyword - Example  class Fred { public:   void inspect() const;   // A const member function – does not change anything   void mutate();          // A non-const member function – changes some stuff in Fred }; int main() {   Fred f;   Fred const * p = &f;   Fred* q = &f;   p->inspect();    // OK: No change to *p   p->mutate();     // Error: Can't change *p via p   q->inspect();    // OK: q is allowed to inspect the object   q->mutate();     // OK: q is allowed to mutate the object   f.inspect();     // OK: f is allowed to inspect the object   f.mutate();      // OK: f is allowed to mutate the object } CS225 Spring 2005

  17. const keyword - Example class Person { public: Person(char* szNewName) { // make a copy of the string m_szName = _strdup(szNewName); } ~Person() { delete[] m_szName; } const char* const GetName() { return m_szName; } private: char* m_szName; }; CS225 Spring 2005

  18. const keyword - Example #include <iostream.h> #include “person.h” void MyBuggyPrint(char* name){ } main() { Person P("Fred Jones"); MyBuggyPrint(P.GetName()); // error! Can't convert const char* const to char* } NOTE: A string within quotes eg. “U of I” is called a string literal and it is of type const char* CS225 Spring 2005

  19. Overloading • Function overloading • Different functions of the same name • Differentiation is through the parameter list • Number of parameters • Type of parameters • const keyword • Return type alone is not enough • Operator overloading • Intuitive meaning of operators like + and - • Customize the meaning of an operator for the class in question • typeoperatorsign(parameters); CS225 Spring 2005

  20. Function overloading - Example #include <iostream.h> class Minus{ public: int subtract (int a, int b) { //used when integer subtraction needs to be done return a-b; } float subtract (float a, float b) { //used when integer subtraction needs to be done return a-b; } }; void main() { Minus mi; int x = 4, y = 2; float m = 7.4, n = 2.3; cout << “Integer subtraction: “ << mi.subtract (x,y) << endl; cout << “Float subtraction: “ << mi.subtract (m,n) << “\n”; //”\n” is the same as endl } CS225 Spring 2005

  21. Operator Overloading – Example by overloading + //complex.h class complex { private: float real; float comp; public: complex (float x, float y); complex operator +(complex b); void print(); }; CS225 Spring 2005

  22. Operator Overloading - Example //complex.C #include “complex.h” complex::complex (float x, float y) { real = x; comp = y; } complex complex::operator +(complex b) { complex result(0,0); result.real = real + b.real; result.comp = comp + b.comp; return result; } void complex::print() { cout << real << “ + “ << comp << “I\n”; } CS225 Spring 2005

  23. Operator Overloading - Example // main.C #include “complex.h” main() { complex *c1 = new complex(1,2); complex *c2 = new complex(7,3); complex c3 = *c1 + *c2; //equivalent to c3 = // (*c1).operator+(*c2); c3.print(); } // output will be 8 + 5i CS225 Spring 2005

  24. Operator overloading This is the list of all operators that can be overloaded. + - * / = < > += -= *= /= << >><<= >>= == != <= >= ++ -- % & ^ ! |~ &= ^= |= && || %= [] () new delete Friend function. Example: While overloading the << operator for the string class (used in mp1), for use by cout, the syntax for usage will be. String s; cout << s; //cout is of type ostream, which is another class. This is the same as saying cout.operator<<(s); Note that operator<< is private to string class. To make this accessible to an ostream object, we have to declare this function as a friend. So, string.h will have a line similar to: friend ostream& operator<< (ostream& Out, const string& ouputString); CS225 Spring 2005

  25. Constructor • Called when new is used • Default constructor class Animal { private: char *name; public: Animal(); Animal(char *name); }; Animal::Animal() { name = NULL; } Animal::Animal (char *inpname) { if (!inpname) { name = new char[MAXNAMESIZE]; strcpy (name, inpname); } else name = NULL; } CS225 Spring 2005

  26. Copy Constructor • When you pass an object by value, or when you explicitly create a new object by passing in an old object to the constructor. • Default provided – memberwise copy • Example: from String.h String(const String& origVal); CS225 Spring 2005

  27. Assignment Operator • a = b = c; • Default provided – memberwise copy • Example: from String.h const String& operator=(const String& origVal); CS225 Spring 2005

  28. Destructor • Called when delete is used • Used to cleanup (e.g. free dynamic memory, close file handles) class Example { Example(); //constructor ~Example(); //destructor } CS225 Spring 2005

  29. Law of the big three • The assignment operator, copy constructor and destructor are inseparable • Generally, if you write one, you have to write the other two. • A new in constructor delete in destructor  copy properly in copy constructor  copy properly in operator= • Side effect: don’t get compiler-supplied default constructor if we implement copy constructor CS225 Spring 2005

  30. Summary • Parameter passing • Reference Variables • const keyword • Function Overloading • Operator overloading • Constructors • Copy constructor • Destructor • Big three law CS225 Spring 2005

More Related