PIC 10A. Lecture 17: Classes III, overloading

Similar documents
Question: How can we compare two objects of a given class to see if they are the same? Is it legal to do: Rectangle r(0,0,3,3);,, Rectangle s(0,0,4,4)

CSCE 110 PROGRAMMING FUNDAMENTALS

Lecture 7. Log into Linux New documents posted to course webpage

Lab 2: ADT Design & Implementation

Object-Oriented Programming in C++

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

FRIEND FUNCTIONS IN CPP

TDDE18 & 726G77. Functions

CS24 Week 3 Lecture 1

CS 247: Software Engineering Principles. ADT Design

Programming Language. Functions. Eng. Anis Nazer First Semester

Programming II Lecture 2 Structures and Classes

Function Overloading

III. Classes (Chap. 3)

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

2 nd Week Lecture Notes

Due Date: See Blackboard

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

CSI33 Data Structures

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

OBJECT ORIENTED PROGRAMMING USING C++

Friends and Overloaded Operators

PIC 10A Objects/Classes

PIC 10A. Lecture 15: User Defined Classes

CSCE 206: Structured Programming in C++

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming

Your first C++ program

Overloading Operators in C++

Friends and Overloaded Operators

Fast Introduction to Object Oriented Programming and C++

CS2141 Software Development using C/C++ Compiling a C++ Program

/************************************************ * CSC 309/404 Review for Final -- Solutions * ************************************************/

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 303: Concepts and Tools for Software Development

Protection Levels and Constructors The 'const' Keyword

EECE.3220: Data Structures Spring 2017

Midterm Exam 5 April 20, 2015

Implementing an ADT with a Class

Circle all of the following which would make sense as the function prototype.

Praktikum: Entwicklung interaktiver eingebetteter Systeme

2. It is possible for a structure variable to be a member of another structure variable.

CSCE Practice Midterm. Data Types

CIS 190: C/C++ Programming. Classes in C++

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. C++ Kitchen Sink. Lecture 14.

Introduction to Classes

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

EECS 183, Week 5. General. Variables I/O. 0. At which location do you have to take the exam? 1. Source code vs. object code? 2. What s a library?

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

Exceptions, Case Study-Exception handling in C++.

Lecture #1. Introduction to Classes and Objects

Object Oriented Programming COP3330 / CGS5409

PIC 10A. Review for Midterm I

CSE 333 Midterm Exam Cinco de Mayo, 2017 (May 5) Name UW ID#

4. Structure of a C++ program

EECS402 Lecture 02. Functions. Function Prototype

COEN244: Class & function templates

CS 1337 Computer Science II Page 1

Object-oriented Programming in C++

CSCS 261 Programming Concepts Exam 2 Fall EXAM 2 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam.

Due Date: See Blackboard. {a n+1 b 2n n 0}

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

CSCS 261 Programming Concepts Exam 2 Fall EXAM 2 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam.

4. C++ functions. 1. Library Function 2. User-defined Function

CE221 Programming in C++ Part 1 Introduction

1) What of the following sets of values for A, B, C, and D would cause the string "one" to be printed?

2. Functions I: Passing by Value

ADTs & Classes. An introduction

CMSC 202 Midterm Exam 1 Fall 2015

PIC 10A. Final Review: Part I

INHERITANCE: CONSTRUCTORS,

Fundamentals of Programming. Lecture 19 Hamed Rasifard

System Design and Programming II

ComS 228 Exam 1. September 27, 2004

Object Oriented Design

Inheritance, and Polymorphism.

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

The development of a CreditCard class

The Compilation Process

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Chapter - 9 Variable Scope and Functions. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1

C++ For Science and Engineering Lecture 15

Software Engineering /48

Operator overloading: extra examples

C++_ MARKS 40 MIN

Due Date: See Blackboard

The University Of Michigan. EECS402 Lecture 02. Andrew M. Morgan. Savitch Ch. 3-4 Functions Value and Reference Parameters.

PIC 10A. Final Review

Exam 2. CSI 201: Computer Science 1 Fall 2016 Professors: Shaun Ramsey and Kyle Wilson. Question Points Score Total: 80

Getting started with C++ (Part 2)

Practicum 5 Maps and Closures

Operator overloading

Solving a 2D Maze. const int WIDTH = 10; const int HEIGHT = 10;

Review: C++ Basic Concepts. Dr. Yingwu Zhu

Lecture on pointers, references, and arrays and vectors

Introduction Of Classes ( OOPS )

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

Computing and Statistical Data Analysis Lecture 3

Programming Abstractions

" Templates for Functions. ! Templates for Data Abstraction. "Syntax for Class Templates. ! This swap algorithm only works for int values:

Transcription:

PIC 10A Lecture 17: Classes III, overloading

Function overloading Having multiple constructors with same name is example of something called function overloading. You are allowed to have functions with same names provided that: 1) They have different number of arguments int foo(int a, int b); int foo(int a); 2) The types of arguments are different. int foo(double a); int foo(int a); It is not enough for return types to be different: void foo(); int foo(); // Illegal

Function overloading double average(double x1, double x2) return (x1+x2)/2; } double average(double x1, double x2, double x3) return (x1+x2+x3)/3; } Now from main I can call either function by: or x = average(a,b); x = average(a,b,c);

Operators are functions too! Operators such as + - % == are nothing but functions that are used with different syntax from normal functions. We don't write +(a,b) we write a+b. Just as you can overload regular functions, you can overload operators. Specifically we want to overload operators for classes!

Comparing classes Wouldn't it be nice if we could compare classes like we compare variables? For example we wrote earlier for products a and b: if (a.is_better_than(b)) // Do stuff } Instead we would like to write: if (a > b) // Do stuff }

Overloading operators We need to define for the computer what it means to compare two classes. We do this by overloading the > operator. In our class declaration we make a small change: class Product public: Product(); void read(); // bool is_better_than(product b) const; bool operator > (Product b) const; void print() const; private: string name; double price; int score; };

This is how we define operator member function bool Product::operator>(Product b) const if (price == 0) return true; if (b.price == 0) return false; return score / price > b.score / b.price; }

Our main gets better while (more) Product next; next.read(); // if (next.is_better_than(best)) if (next > best) best = next; } cout << "More data? (y/n) " ; string answer; getline(cin, answer); if (answer!= "y") more = false;

More about operators for classes We can overload other operators as well. Without knowing we have already been using one other overloaded class operator: string name = "Homer " + "Simpson"; + is overloaded for the string class. We could overload >=,==, *, +, - even %.

Rectangle class example Lets overload == for our Rectangle class. class Rectangle public: Rectangle(); Rectangle(Point new_leftcorner, double new_height, double new_width); void move(double dx, double dy); void draw(); bool operator == (Rectangle r); private: Point LeftCorner; double width; double height; };

== for Rectangles When should we consider a Rectangle R1 equal to Rectangle R2? There are many ways one could do it. We will compare their areas. bool Rectangle::operator == (Rectangle r) if (height * width == r.height * r.width) return true; else return false; }

How do we use == in main? if (R1 == R2) // Do stuff }

Passing classes to functions When an instance of a class is passed to a function by default it is passed by value just as any ordinary variable. If you want your functions to change your object you need to pass it by reference. void foo (Point &P) P.move(1.0, 3.9); } There are other reasons to pass your object by reference. Making a copy of a class costs a lot of overhead.

Separate compilation Structure of our programs looks like this: #include <libraries> using namespace std; class declarations }; class member functions function declarations program functions main routine Help! Its getting crowded in this.cpp file!

Reasons to split your code into files Make your files shorter Improve organization Make your files easier to read When the compiler runs it only recompiles the files that have changed When working in a team each person can be responsible for their own file

What your header file should contain Your class declarations Declarations of nonmember functions (prototypes) Declarations of global variables declaration of constants (global) In general we put declarations of all shared stuff.

The source file contains Definitions of member functions Definitions of non-member functions Definitions of global variables In general the source file implements everything that the header file declared. Note: This source file does not contain main!!

Product class example We will brake our product class into three separate files. product.h This will contain our product class declarations product.cpp This will contain all the member functions product_main.cpp This file will contain the main routine

product.h #ifndef PRODUCT_H #define PRODUCT_H #include <string> using namespace std; class Product public: Product(); void read(); bool is_better_than(product b) const; void print() const; private: string name; double price; int score; }; #endif This closes the first line These lines guard against multiple inclusions of product.h Any time we include a standard library we also have to have a using namespace std;

product.cpp #include <iostream> #include "product.h" using namespace std; Main thing to note here is that we have to include product.h here. Product::Product() price = 1; score = 0; } /* And all the other member functions... */

product_main.cpp #include <iostream> #include "product.h" int main() Product best; We of course need to include product.h in our main cpp file to use the product class. bool more = true; while (more) Product next; next.read(); // ETC. Why don't we just write the main into the product.cpp file?

Separate compilation graphics example See separate compilation example for our rectangle class.