.Open CSci202 Computer Science II, Session 07, Inheritance (Previous): C++ Classes .See http://www/dick/cs202/06.html . Input -- Overloading and operators 11 Operator Overloading; String and Array Objects 578 11.1 Introduction 11.2 Fundamentals of Operator Overloading 11.3 Restrictions on Operator Overloading 11.4 Operator Functions as Class Members vs. Global Functions 11.5 Overloading Stream Insertion and Stream Extraction Operators 11.6 Overloading Unary Operators 11.7 Overloading Binary Operators 11.8 Case Study: Array Class 11.9 Converting between Types 11.10 Case Study: String Class 11.11 Overloading ++ and -- 11.12 Case Study: A Date Class 11.13 Standard Library Class string 11.14 explicit Constructors 11.15 Wrap-Up . Assigned Work Due -- Question on Reading . What are unary, binary, and ternary operators? A unary operator has one argument, a binary operator has two, and a ternary operator has three. .As_is ++i .As_is 1+i .As_is i?0:1 . Chapter 10 pages 534 -- Question mark I am still somewhat confused about what what the "?" does. they are used in the class definitions for the get and set functions on this page. can you please elaborate? .List The "?" must have a ":". Together they make a ternary operator. Example -- find the biggest of two numbers .As_is x > y ? x : y Syntax .As_is condition ? ifTrueExpression : ifFalseExpression Semantics ( c ? x : y ) means if c is true then evaluate x else evaluate y. Exercise -- write expression to give the smallest of two numbers. Also study .See ./05.html#conditional expression .See ./glossary.html#conditional .Close.List . Chapter 11 pages ppp-ppp -- Overloading Is overloading ever ok? You used it in your first programs without even noticing it. It makes life a lot easier for the programmer who uses overloaqded functions. It just takes a little care to avoid compilation errors and occasional surprises. The real question is: when should you not overload an operator or function. And the answer is -- when the result will surprise the programmer who uses the overloaded function or operator. Example, when .As_is a+b turns the screen blue. Or if "sin" calculated "tan"! This is evil coding and should be avoided. . Chapter 11 pages 579-580 -- Operator Overloading What is operator overloading and how can it make programs more readable and programming more convenient? What exactly does overloading them do? Overloading allows C/C++/Java to use the same symbol to represent different operations depending on the data. The symbol has a context-dependent meaning. Most operators in C++ have subtly different operations -- machine code operations -- depending on what data you provide. C++ also lets you give your own, new, meaning to most of the existing operators when they operate on you data. The alternative is to have a language like APL that uses most of the Greek alphabet: \alpha, \beta, \beta, plus various strange characters to represent all the different operations that we need for complex (mostly mathematical) programs. . Chapter 11 pages -- Overloading What exactly is the code that overloads operators. When you provide a definition of a function or operator that already exists then it is overloaded. It often arrives in two parts -- the prototype in a class and then, later a complete declaration. . Chapter 11 pages -- Operation overloading Can you explain the use for overloading operators such as "+", "-", and "="? Suppose you are a mathematician work with an additive group.... then you will want to define your own meanings for addition and subtraction. Or suppose you are working on a program that understands different units -- Feet, Inches, Yards, .... etc then you will need to define addition for Feet, Inches, Yards, etc... You might add some type conversions to make Feet into Inches as well. If NASA had done this with their Mars probe perhaps they might have not missed the planet! . Chapter 11 pages 581 -- Restrictions on Operator Overloading Can you give an example of how to overload a operator? Suppose we are defining a class of Points on a plain with x and y co-ordinates. We might decide that we need to know how far to points are from each other. We could choose to use the "-" operator to symbolize this .As_is friend double operator-(Point p1, Point p2) { return sqrt( ..... ); } Or perhaps we want to use the "+" symbol to add Tunes to our Library: .As_is void Library::operator+(Tune & t) { ...... } The commonest overloading is for << and >>. Example in lab. . Chapter 11 pages 581 -- Restrictions on Operator Overloading in what context might the name operator / be used? Mostly we use the syntax .As_is operator ??? ( ..... ) when we define a new meaning for the operator "???". There is another advanced use when we wish to pass the operator to an STL algorithm.... later. We will pprobably skip this use. . Chapter 11 pages 583 -- Overloading assignment operators and arrows What is ->, and how does one overload it? The arrow operator is not an assignment. It works (normally) between a pointer and a member of a class: .As_is pointer -> function(data) .As_is pointer -> attribute In both cases the pointer is de-referenced and then the member function/attribute is applied to the resulting object.... more next class. I'm not sure of how to overload it and would have to look the best syntax up in the C++ reference manual or a text. By the way -- the -> operator is commonly one of the functions use with what are called iterators -- objects that mimic pointers and provide access to items in a complex data structure. . Chapter 10 pages 583 -- Functions Could you go over operators as member functions and global functions ?? Can u please explain more about class member and global functions? So-called Global functions are not attached to objects. They are called like this .As_is function ( data ) Member functions are attached to objects and are called like this .As_is object.function(data) or .As_is pointer -> function(data) For example in the the STL class string we have a member function 'size', and in the cmath library we have a global function 'sin'. A function in a class is a member function..... unless it is named a "friend" or "static". . Chapter 11 pages 583 -- Operators Why must the operator overloading function be declared as a class member when overloading? It does not have to be a member of the class.... it can be a friend. . Chapter 11 pages 583-584 -- General overloading Could you give some examples of what overloading is used for? Can it be used for formatting input from the user? Also, could you give some examples of how the code is written and implemented? -- I'm kind of confused by this. I'll see what I can fake in the way of simple examples .See ./overloading.cpp The classic technique is to overload operator>> so that it sorts out formatted input from the user. The actual code can get complicated because users can be quite inventive about supplying input. One regular problem is the user inputting digits and the program has to generate a double or an int. My favorite trick for this will be covered later in the book (18.10) and uses string-streams. I wrote some notes on this for CSci201 .See http://csci.csusb.edu/dick/cs201/string.html#How can I convert numbers to strings and strings to numbers if you need some examples now. . Chapter 10 pages 548-549 -- Friend Function and friend classes I understand the friend function in C++ and what it does, but can you write out an example code, so I can further understand this function? .See ./friend.cpp . Chapter 11 pages 576 -- Operator Functions as Class Members vs. Global Functions How should I know when to overload an operator as a member function, or as a global function? It is subtle. I don't expect you to master this in this class. I'm not 100% on it myself. But I do have some rules. (1) << and >> should be friends and the book explains why. (2) Just about every thing else should be a member function of the class. . Chapter 11 pages 585-587 -- Overloading Stream Insertion and Stream Extraction Operators Can you explain the phone number program? (Figure 11.3-11.5) Given time I'll give a verbal tour. . Chapter 11 pages 584 -- overloading stream extraction operator In the case of: .As_is friend ostream &operator<<(ostream&, const PhoneNumber &) means that the "<<" is being overloaded and what else? THis says that you will provide a detailed description of how to output a PhoneNumber to an output stream, later. One defined your program can .As_is cout << anyPhoneNumber; It will also confirm to the usual property of "<<" of being able to write a chain a series of output: .As_is cout << "Home phone is " << homePhone << " and mobile phone is " << mobilePhone << endl; . Chapter 11 pages 585 -- Stream Insertion and Extraction Operators .As_is friend ostream &operator<<( ostream &, const PhoneNumber & ); .As_is friend istream &operator>>( istream &, PhoneNumber & ); Is the '&operator' and 'ostream &' and 'istream &' just a naming convention? Or is that just how you are supposed to write it? Yes! I always copy the heading.... put the two headers on your "cheat sheet" for use in quizzes and/or final. However the notation is based on the use of the "&" symbol to indicate references. It indicates that you must provide a reference to a stream (not a copy) and it will return another reference that cal be used in the next operation on the left... . Chapter 11 pages 588 -- overloading operators What operators can/cannot be overloaded? Most of them. Not ".", ".*", "::"., and "?:". See page 581. . Chapter 11 pages 589 -- class Can a class be assigned to more than one array object? For just about every class -- you can construct as many objects of that class as you need or until you run out of RAM/memory. So there can be many Array objects existing at once. . Chapter 11 pages 590 -- Operator Overloading What is the difference between .As_is int &operator[](int); .As_is int operator[](int) const; The first lets you write .As_is object[foo] = mumble ; Both let you write .As_is foobar = ..... object[ foo ] .....; However, the second form will give you faster and saver program. . Chapter 11 pages 602 -- Type conversion vs type conversion operators Is converting between types common? and do you recommend it? You can hardly avoid converting one type of data to another in a program... writing special operators to do it automatically is something you do when you think it has value. I personally have never done it. But if you have a problem whose solution is simplified by defining a .Key cast operator then you should dig out a text book or reference manual and carefully code one. Here is a sample of converting a Date to a string ready for output .See ./conversion.cpp that also shows a clever way to convert numbers into strings... . Chapter 11 pages 579-628 -- Conversion Operators Can you elaborate on the functionality of Conversion Operators please? The purpose of a Conversion operator is to let the computer convert an object you have defined into some other type of object. This can happen automatically if that is the only way for an expression to make sense -- this is called "coercion". It can also be invoked by various "cast" operators. consider them to be convenient rather than essential. I also suspect that they can lead to confusing result sometimes. I typically grit my teeth about the inconvenient code rather than set up a type convertion in my classes. However I'm thinking about thevalue of always having a string version of every type of object that I have.... ready for output. I'm going to think about this.... . Demo a class with const, friend, operators Complete a given simple efficient 8 character buffer class for secure input/output. Previously you met a very insecure 8 character buffer in .See ./lab03.html because it allowed stupid programmers to do stupid things ... like over-running the end of the buffer. One way to fix this is to hide the dangerous data in a class and provide just those functions that do what is needed and can't be abused. UML: .Image Buffy.png class Buffy in UML Here is the test program: .See http://www/dick/cs202/testBuffy.cpp Here is the "Header file": .See http://www/dick/cs202/Buffy.h . Demo Splitting a header file from a body file and using make The above was done is the simplest way -- very amateurish. Now to redo it using professional techniques: we separate the detailed code of the functions from the header file and precompile them. Then we use a program called .Key make to assemble the program for use. .See http://www/dick/cs202/testBuff2.cpp .See http://www/dick/cs202/Buff2.h .See http://www/dick/cs202/Buff2.cpp .See http://www/dick/cs202/Makefile .See http://www/dick/cs202/resources.html#Make .Close . Exercises .List Draw UML diagram of C++ classes Write a class for a given UML class .Close.List . Lab .See http://www/dick/cs202/lab04.html where you will create a safe array class. .Close CSci202 Computer Science II, Session 07, Inheritance (Next): Project 2 is due and a quiz on everything about classes including inheritance. See .See http://www/dick/cs202/08.html for details.