Friend functions, operator overloading

Slides:



Advertisements
Similar presentations
Chapter 11 Separate Compilation and Namespaces. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Separate Compilation.
Advertisements

Copyright © 2002 Pearson Education, Inc. Slide 1.
An introduction to pointers in c
DATA STRUCTURES Lecture: Interfaces Slides adapted from Prof. Steven Roehrig.
Operator Overloading Fundamentals
Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
Lecture 18 Templates, Part II. From Last Time: What is a Template? This is the “official” specification for a template. It says that to define a template.
Class and Objects.
Week 2: Primitive Data Types 1.  Programming in Java  Everything goes inside a class  The main() method is the starting point for executing instructions.
Review of C++ Programming Part II Sheng-Fang Huang.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
4.1 Instance Variables, Constructors, and Methods.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
Operator Overloading Version 1.0. Objectives At the end of this lesson, students should be able to: Write programs that correctly overload operators Describe.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
1 Today’s Objectives  Announcements Homework #3 is due on Monday, 10-Jul, however you can earn 10 bonus points for this HW if you turn it in on Wednesday,
By Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 13 More on Classes Chapter 8 Week 13 More on Classes Chapter 8.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Computing and Statistical Data Analysis Lecture 6 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Introduction to classes and objects:
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
1 C++ Classes & Object Oriented Programming Overview & Terminology.
Computer Programming II Lecture 5. Introduction to Object Oriented Programming (OOP) - There are two common programming methods : procedural programming.
Object Oriented Programming COP3330 / CGS5409.  Arithmetic Operator Overloading  Increment (++) / Decrement (--)  In-class exercise.
External Scope CECS 277 Mimi Opkins.
Memory Management.
Operator Overloading.
Operator Overloading Introduction
EGR 2261 Unit 13 Classes Read Malik, Chapter 10.
Learning Objectives Pointers as dada members
Friend functions.
Java Unit 11: Inheritance I
User-Written Functions
Classes and Objects.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Motivation and Overview
Object Oriented Programming COP3330 / CGS5409
Classes & Objects.
Operator Overloading BCA Sem III K.I.R.A.S.
Stack Data Structure, Reverse Polish Notation, Homework 7
CISC/CMPE320 - Prof. McLeod
Classes and Objects 2nd Lecture
Lecture 4-7 Classes and Objects
Phil Tayco Slide version 1.0 Created Oct 2, 2017
Object Oriented Programming COP3330 / CGS5409
Number and String Operations
Classes and Objects.
Coding Concepts (Data- Types)
Operator Overloading.
CISC/CMPE320 - Prof. McLeod
CISC/CMPE320 - Prof. McLeod
Operator Overloading Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Fall 2018 CISC124 2/24/2019 CISC124 Quiz 1 marking is complete. Quiz average was about 40/60 or 67%. TAs are still grading assn 1. Assn 2 due this Friday,
COP 3330 Object-oriented Programming in C++
COP 3330 Object-oriented Programming in C++
Java Programming Language
Submitted By : Veenu Saini Lecturer (IT)
Primitive Types and Expressions
Winter 2019 CISC101 4/28/2019 CISC101 Reminders
(4 – 2) Introduction to Classes in C++
C++ Object Oriented 1.
11.1 The Concept of Abstraction
Presentation transcript:

Friend functions, operator overloading

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.

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.

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.

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).

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

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.

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.

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;

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.

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.

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;

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).

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.

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.

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.

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.

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.

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".