cs60 Discussion week9 Lastweek Bitoperators Buffered IO Overloading operators Overview Standard class virtual methods templates Standard Class Builtin simple types int, char, double, ... Builtin constructed types struct/union What operations are available to *all* builtin types 1. Can I compare 2 structs? 2. Can I assign --> creation/assignment/destruction What operations are available to *all* numeric types + - / * % comparison What operations are available to *all* integer types & ^ | ~ C++ allows programmer to add types that seem built-in How? compare int to class Num { int *values; }; 0 main() { int a; //create an unitialized int Num n; // create ... Num int a[10]; Num n[10]; } class Num { public: Num(); }; 1. The 'default constructor' allows simple declarations and *arrays* to be defined.... What about initialized ints --------------------------- main() { int a (1), b = 1; //create an itialized int Num n(1), m = 1; // create ... Num Num x = n; } class Num { public: Num(); Num (const Num&x); }; 1. The 'copy-constructor' allows objects to be initialized from other object of the same type. Assignment and comparison --------------------------- main() { int a; Num x, y; a = 2; x = y; if (a < b) {...} if (x < y) { } } // Big number class class Num { public: Num(); Num(const Num&); ~Num(); Num& operator = (const Num&); bool operator == (const Num&); bool operator < (const Num&); }; 1. The 'assignment operator' allow the assignment of the type. 2. Why does it take 'const Num&' and why does it return Num& viritual functions ------------------ Java/C++ support polymorphism class Graphic { virtual void draw (); }; class Rect : public Graphic virtual void draw (); } class Circle : public Graphic virtual void draw (); } A polymorphic call is made to the object based on it's type. Graphic *items[10] items[0] = new Circle(); items[1] = new Rect(); for (int i=0; i<10; i++) items[i]->draw(); // Calls whats? 1. You must declare the each function virtual 2. The base class must be declared virtual How about deletion of the the object? for (int i=0; i<10; i++) delete items[i]; // Calls which one??? 1. You need to add a virtual destructor class Graphic { virtual ~Graphic(); }; 2. Can constructors be virtual? Abstract class -------------- A class that is a base class for other (polymorphic) but may not be constructed class Graphic { virtual draw () = 0; } Graphic *g = new Graphic(); // ERROR Graphic *g = new Rect (); // OK has a draw method defined.