Presentation is loading. Please wait.

Presentation is loading. Please wait.

Friend functions, operator overloading

Similar presentations


Presentation on theme: "Friend functions, operator overloading"— Presentation transcript:

1 Friend functions, operator overloading

2 It’s good to have friends
A friend function of a class is defined outside the class’s scope (I.e. not member functions), yet has the right to access the non-public members of the class. Single functions or entire classes may be declared as friends of a class. These are commonly used in operator overloading. Perhaps the most common use of friend functions is overloading << and >> for I/O.

3 Friends Basically, when you declare something as a friend, you give it access to your private data members. This is useful for a lot of things – for very interrelated classes, it more efficient (faster) than using tons of get/set member function calls, and they increase encapsulation by allowing more freedom is design options.

4 Friends A class doesn't control the scope of friend functions so friend function declarations are usually written at the beginning of a .h file. Public and private don't apply to them.

5 Friends (a few gory details)
Friendship is not inherited, transitive, or reciprocal. Derived classes don’t receive the privileges of friendship (more on this when we get to inheritance in a few classes) The privileges of friendship aren’t transitive. If class A declares class B as a friend, and class B declares class C as a friend, class C doesn’t necessarily have any special access rights to class A. If class A declares class B as a friend (so class B can see class A’s private members), class A is not automatically a friend of class B (so class A cannot necessarily see the private data members of class B).

6 Friends class someClass { friend void setX( someClass&, int);
int someNumber; … rest of class definition } // a function called setX defined in a program void setX( someClass &c, int val) { c.someNumber = val; } // inside a main function someClass myClass; setX (myClass, 5); //this will work, since we declared // setX as a friend

7 Operator Overloading So far, we’ve seen that we can overload functions – two functions that have the same name can co-exist, as long as the compiler can tell the difference between them. This also happens with operators, both unary (!, ++, etc.) and binary ( +, -, *, %,). The one ternary operator ( ? ) cannot be overloaded.

8 Operator overloading C++ actually has this built into the language, and you’ve been using it already. When you call the addition operator with two integers, and when you call the addition operator with two floating point numbers, calls a completely different function.

9 Operator overloading Sometimes, when we are defining a class, it might be useful to define some addition operators. Note, this is usually a convenience – the same functionality can usually be accomplished through simple member calls. So, let’s say we have a class called simpleExample. What does the following code do? simpleExample se1(54,3), se2(43,3); se1+=se2;

10 Operator Overloading The result of the previous will be whatever we defined the += operator to do for the simpleExample class. One operator ( =, the assignment operator) is automatically overloaded for classes you create.

11 Quick, simple example The next lecture will be more focused on how to write these, but at this point, I just want to show a very simple example of how to do this. Define a function with the keyword "operator" preceding the operator. There can be whitespace between operator and the operator, but usually they are written together.

12 Quick, simple example // Point.h file Point operator+(Point p) const;
//Point.cc file Point Point::operator+(Point p) const { return Point(x+p.x, y+p.y); } //some main Point a(10, 20); Point b(1, 2); Point c = a + b;

13 Restrictions on overloading
Most operators can be overloaded. A few of them can’t – the . (dot) operator, the .* operator, the unary scope :: operator, the ?: operator, and the sizeof() call, which is technically an operator. You can’t change the precedence of operators. You can’t create your own operators (some people would like to overload ** to do exponation – you can’t).

14 Restrictions on overloading
Also note that each operator is unique – defining an addition (“+”) operator for your class does not automatically define “+=“, even though they should do practically the same work. Also note that preincrement (++a) and postincrement (a++) are two separate operators – I’ll show you how to differentiate the two next lecture.

15 Overloading – when/why
Overloading can be a good thing when it increases the clarity/ease of which your class can be used. The Rational Number class is a great example. Each “rational” object represents a number in fraction form, basically storing an numerator and denominator. Well, overloading the + operator should be obvious – so this would be a good use.

16 Overloading – when/why
Don't use operator overloading just because it can be done and is a clever trick. The purpose of operator overloading is to make programs clearer by using conventional meanings for ==, [], +, etc. This is purely a convenience to the user of a class. Operator overloading isn't strictly necessary unless other classes or functions expect operators to be defined (as is sometimes the case). Whether it improves program readability or causes confusion is more a case of how well you use it. In any case, C++ programmers are expected to be able to use it -- it's the C++ way.

17 Overloading – why/when
Abusing overloading makes a really great way to confuse your program. The following ideas are from a a website called “How to Write Unmaintainable code” (there is a link to it off of my CISC370 page, if you’re interested). This is satire for things to not do.

18 Overloading why/when Choosing The Best Overload Operator
In C++, overload +,-,*,/ to do things totally unrelated to addition, subtraction etc. After all, if the Stroustroup can use the shift operator to do I/O, why should you not be equally creative? If you overload +, make sure you do it in a way that i = i + 5; has a totally different meaning from i += 5; Here is an example of elevating overloading operator obfuscation to a high art. Overload the '!' operator for a class, but have the overload have nothing to do with inverting or negating. Make it return an integer. Then, in order to get a logical value for it, you must use '! !'. However, this inverts the logic, so [drum roll] you must use '! ! !'. Don't confuse the ! operator, which returns a boolean 0 or 1, with the ~ bitwise logical negation operator.

19 Overloading why/when Overload new
: Overload the "new" operator - much more dangerous than overloading the +-/*. This can cause total havoc if overloaded to do something different from it's original function (but vital to the object's function so it's very difficult to change). This should ensure users trying to create a dynamic instance get really stumped. You can combine this with the case sensitivity trick: also have a member function, and variable called "New".


Download ppt "Friend functions, operator overloading"

Similar presentations


Ads by Google