CS 541 Lecture -*- Outline -*- * Overloading All functions and operators can be overloaded (main exception is ".") cannot change syntax cannot define new operators no special declaration (in 2.0) Full name can be used, e.g. operator+(2,3) Operator must be a member function or take one class object as argument (except new, delete, or delete[]) prevents redefining built-in operators Binary operators can be member function with one argument, (a.operator+(b)) friend function with two arguments (operator+(a,b)) but not both! Unary operators can be member function with no arguments, (a.operator--()) friend function with one arguments (operator--(a)) but not both! = and & have default meanings operator= is memberwise assignment by default can overload and put in private part to prevent assignment. Tries to find most specific implementation. ** overloading constructors to get conversions constructors with single arguments function as type conversions implicit! applied only if unique ---------- class complex { public: complex(double r) {re = r; im=0;} private: double re, im; }; main() { // explicit conversion complex z1 = complex(23.0); // implicit coercion complex z2 = 27; } ---------- conversion operators can be used to deal with the base types ------- class tiny { public: tiny(int i) { assign(i); } tiny(tiny& t) { v = t.v; } int operator=(tiny& t) { return v = t.v; } int operator=(int i) { return assign(i); } operator int() { return v; } private: char v; int assign(int i) { extern void error(); if (i & (~63)) v = i; else { error(); v = 0;} return v; } }; // can mix int and tiny's in expressions ------- Only one level of conversion is implicit ambiguity in applying coercions is illegal Assignment (operator=) can be overloaded, different than initialization which is classname(const classname&) function