More C++ Concepts. Operator overloading Friend Function This Operator Inline Function

Similar documents
13 Classes & Objects with Constructors/Destructors

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

C++ Crash Kurs. C++ Object-Oriented Programming

A Summary of Operator Overloading

C++ Overloading, Constructors, Assignment operator

C++ INTERVIEW QUESTIONS

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) {

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

El Dorado Union High School District Educational Services

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Object Oriented Software Design II

Function Overloading I

Basics of I/O Streams and File I/O

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Moving from CS 61A Scheme to CS 61B Java

Object Oriented Software Design II

An Incomplete C++ Primer. University of Wyoming MA 5310

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Subject Name: Object Oriented Programming in C++ Subject Code:

Schedule. Structures and Classes in C++ Outline. Goals for This Topic. Another Example of a Structure. What is a Structure? Classes May 12-17, 2005

Sources: On the Web: Slides will be available on:

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

Basics of C++ and object orientation in OpenFOAM

Constructor, Destructor, Accessibility and Virtual Functions

Class 16: Function Parameters and Polymorphism

Advanced Data Structures

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

Stack Allocation. Run-Time Data Structures. Static Structures

! " # $ %& %' ( ) ) *%%+, -..*/ *%%+ - 0 ) 1 2 1

Description of Class Mutation Mutation Operators for Java

Course notes Standard C++ programming

C++ Support for Abstract Data Types

Ch 7-1. Object-Oriented Programming and Classes

Comp151. Definitions & Declarations

Binary storage of graphs and related data

Glossary of Object Oriented Terms

Subtopics - Functions Function Declaration Function Arguments Return Statements and values. By Hardeep Singh

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Data Structures using OOP C++ Lecture 1

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

N3458: Simple Database Integration in C++11

Chapter 13 Storage classes

CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator=

Chapter One Introduction to Programming

Object Oriented Software Design II

C++ Input/Output: Streams

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

1.1.3 Syntax The syntax for creating a derived class is very simple. (You will wish everything else about it were so simple though.

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

C++ Essentials. Sharam Hekmat PragSoft Corporation

Java Interview Questions and Answers

The C Programming Language course syllabus associate level

OpenCL Static C++ Kernel Language Extension

Introduction to Programming Block Tutorial C/C++

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Compiler Construction

Member Functions of the istream Class

Conversion Constructors

A deeper look at Inline functions

1. Polymorphism in C++...2

Coding conventions and C++-style

CS11 Advanced C++ Spring Lecture 9 (!!!)

C++ Programming Language

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

CISC 181 Project 3 Designing Classes for Bank Accounts

The programming language C. sws1 1

Parameter Passing. Standard mechanisms. Call by value-result Call by name, result

C++FA 5.1 PRACTICE MID-TERM EXAM

AP Computer Science Java Subset

Habanero Extreme Scale Software Research Project

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Computer Programming C++ Classes and Objects 15 th Lecture

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

6. Control Structures

CORBA Programming with TAOX11. The C++11 CORBA Implementation

Chapter 5 Functions. Introducing Functions

Lesson Name: Introduction of OOP

Sequential Program Execution

PL / SQL Basics. Chapter 3

OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES CONSTRUCTORS AND DESTRUCTORS

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Implementation Aspects of OO-Languages

Chapter 5 Names, Bindings, Type Checking, and Scopes

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Symbol Tables. Introduction

Applied Informatics C++ Coding Style Guide

Copyright 2001, Bill Trudell. Permission is granted to copy for the PLoP 2001 conference. All other rights reserved.

5 CLASSES CHAPTER. 5.1 Object-Oriented and Procedural Programming. 5.2 Classes and Objects 5.3 Sample Application: A Clock Class

Transcription:

More C++ Concepts Operator overloading Friend Function This Operator Inline Function 1

Review There are different types of member functions in the definition of a class Accessor int Str :: get_length(); implementor/worker void Rectangle :: set(int, int); helper void Date :: errmsg(const char* msg); constructor Account :: Account(); Account :: Account(const Account& a); Account :: Account(const char *person); destructor Account :: ~Account(); 2

Operator overloading Programmer can use some operator symbols to define special member functions of a class Provides convenient notations for object behaviors 3

Why Operator Overloading int i, j, k; // integers float m, n, p; // floats k = i + j; // integer addition and assignment p = m + n; // floating addition and assignment The compiler overloads the + operator for built-in integer and float types by default, producing integer addition with i+j, and floating addition with m+n. We can make object operation look like individual int variable operation, using operator functions Date a,b,c; c = a + b; 4

Operator Overloading Syntax Syntax is: operator@(argument-list) --- operator is a function Examples: operator+ operatoroperator* operator/ --- @ is one of C++ operator symbols (+, -, =, etc..) 5

Example of Operator Overloading class CStr { char *pdata; int nlength; public: // void cat(char *s); // friend CStr operator+(cstr str1, CStr str2); friend CStr operator+(cstr str, char *s); friend CStr operator+(char *s, CStr str); void CStr::cat(char *s) { int n; char *ptemp; n=strlen(s); if (n==0) return; ptemp=new char[n+nlength+1]; if (pdata) strcpy(ptemp,pdata); }; //accessors char* get_data(); int get_len(); } strcat(ptemp,s); pdata=ptemp; nlength+=n; 6

The Addition (+) Operator CStr operator+(cstr str1, CStr str2) { CStr new_string(str1); //call the copy constructor to initialize an entirely new CStr object with the first operand new_string.cat(str2.get_data()); //concatenate the second operand onto the end of new_string return new_string; //call copy constructor to create a copy of the return value new_string } new_string str1 strcat(str1,str2) strlen(str1)+strlen(str2) 7

How does it work? CStr first( John ); CStr last( Johnson ); CStr name(first+last); CStr operator+(cstr str1,cstr str2) { CStr new_string(str1); new_string.cat(str2.get()); return new_string; } name Copy constructor John Johnson Temporary CStr object 8

Implementing Operator Overloading Two ways: Implemented as member functions Implemented as non-member or Friend functions the operator function may need to be declared as a friend if it requires access to protected or private data Expression obj1@obj2 translates into a function call obj1.operator@(obj2), if this function is defined within class obj1 operator@(obj1,obj2), if this function is defined outside the class obj1 9

Implementing Operator Overloading 1. Defined as a member function class Complex {... public:... Complex operator +(const Complex &op) { double real = _real + op._real, imag = _imag + op._imag; return(complex(real, imag)); }... }; c = a+b; c = a.operator+ (b); 10

Implementing Operator Overloading 2. Defined as a non-member function class Complex {... public:... double real() { return _real; } //need access functions double imag() { return _imag; }... }; c = a+b; c = operator+ (a, b); Complex operator +(Complex &op1, Complex &op2) { double real = op1.real() + op2.real(), imag = op1.imag() + op2.imag(); return(complex(real, imag)); 11 }

Implementing Operator Overloading 3. Defined as a friend function class Complex {... public:... friend Complex operator +( const Complex &, const Complex & );... }; c = a+b; c = operator+ (a, b); Complex operator +(Complex &op1, Complex &op2) { double real = op1._real + op2._real, imag = op1._imag + op2._imag; return(complex(real, imag)); 12 }

What is Friend? Friend declarations introduce extra coupling between classes Once an object is declared as a friend, it has access to all non-public members as if they were public Access is unidirectional If B is designated as friend of A, B can access A s non-public members; A cannot access B s A friend function of a class is defined outside of that class's scope 13

More about Friend The major use of friends is to provide more efficient access to data members than the function call to accommodate operator functions with easy access to private data members Friends can have access to everything, which defeats data hiding, so use them carefully Friends have permission to change the internal state from outside the class. Always recommend use member functions instead of friends to change state 14

Assignment Operator Assignment between objects of the same type is always supported the compiler supplies a hidden assignment function if you don t write your own one same problem as with the copy constructor - the member by member copying Syntax: class& class::operator=(const class &arg) { // } 15

Example: Assignment for CStr class Assignment operator for CStr: CStr& operator=(const CStr & source) Return type - a reference to (address of) a CStr object Argument type - a reference to a CStr object (since it is const, the function cannot modify it) CStr& operator=(const CStr &source){ //... Do the copying return *this; Assignment function is called as a } member function of the left operand =>Return the object itself str1=str2; str1.operator=(str2) 16

Overloading stream-insertion and stream-extraction operators In fact, cout<< or cin>> are operator overloading built in C++ standard lib of iostream.h, using operator "<<" and ">>" cout and cin are the objects of ostream and istream classes, respectively We can add a friend function which overloads the operator << friend ostream& operator<< (ostream &ous, const Date &d); ostream& operator<<(ostream &os, const Date &d) { os<<d.month<< / <<d.day<< / <<d.year; return os; cout ---- object of ostream } cout<< d1; //overloaded operator 17

Overloading stream-insertion and stream-extraction operators We can also add a friend function which overloads the operator >> friend istream& operator>> (istream &in, Date &d); istream& operator>> (istream &in, Date &d) { char mmddyy[9]; in >> mmddyy; // check if valid data entered if (d.set(mmddyy)) return in; cin ---- object of istream cout<< "Invalid date format: "<<d<<endl; exit(-1); } cin >> d1; 18

The this pointer Within a member function, the this keyword is a pointer to the current object, i.e. the object through which the function was called C++ passes a hidden this pointer whenever a member function is called Within a member function definition, there is an implicit use of this pointer for references to data members this Data member reference Equivalent to pdata nlength pdata this->pdata nlength this->nlength CStr object (*this) 19

Inline functions An inline function is one in which the function code replaces the function call directly. Inline class member functions if they are defined as part of the class definition, implicit if they are defined outside of the class definition, explicit, I.e.using the keyword, inline. Inline functions should be short (preferable one-liners). Why? Because the use of inline function results in duplication of the code of the function for each 20 invocation of the inline function

class CStr { char *pdata; int nlength; public: Inline functions within class declarations char *get_data(void) {return pdata; }//implicit inline function int getlength(void); }; inline void CStr::getlength(void) //explicit inline function { return nlength; } Example of Inline functions Inline functions outside of class declarations int main(void) { char *s; int n; CStr a( Joe ); s = a.get_data(); n = b.getlength(); } In both cases, the compiler will insert the code of the functions get_data() and getlength() instead of generating calls to these functions 21

Inline functions (II) An inline function can never be located in a run-time library since the actual code is inserted by the compiler and must therefore be known at compile-time. It is only useful to implement an inline function when the time which is spent during a function call is long compared to the code in the function. 22

Take Home Message Operator overloading provides convenient notations for object behaviors There are three ways to implement operator overloading member functions normal non-member functions friend functions 23

24