CSC 330 Object Oriented Programming. Operator Overloading Friend Functions & Forms

Size: px
Start display at page:

Download "CSC 330 Object Oriented Programming. Operator Overloading Friend Functions & Forms"

Transcription

1 CSC 330 Object Oriented Programming Operator Overloading Friend Functions & Forms 1

2 Restrictions on Operator Overloading Most of C++ s operators can be overloaded. Operators that can be overloaded + - * / % ^ & ~! = < > += -= *= /= %= ^= &= = << >> >>= <<= ==!= <= >= && >*, -> [] () new delete new[] delete[] No new operators can be created Use only existing operators 2

3 Arithmetic Operators 3

4 Comparison Operators 4

5 Logical Operators 5

6 Bitwise Operator 6

7 Other Operators 7

8 Examples of Bitwise Operators 8

9 Restrictions on Operator Overloading cont d Arity (number of operands) cannot be changed Unary operators remain unary, and binary operators remain binary Operators &, *, + and - each have unary and binary versions Unary and binary versions can be overloaded separately 9

10 Overloading Operators The Rules Associativity refers to the order in which actions within an expression are carried out You cannot change associativity when you overload operators You also cannot change the normal precedence of any operator 10

11 Overloading Operators The Rules 11

12 A Complex Class #include <iostream> class Complex { double real; double image; public: Complex(double re=0, double im=0) { this->real = re; this->image = im; Complex add(const Complex& c) const { Complex result; result.real = this->real + c.real; result.image = this->image + c.image; return result;.... ; 12

13 Using the Complex Class int main() { Complex z(1,2), w(3,4); Complex a = z.add(w); a.display(); // want a = z+w (4,6) 13

14 Operator Functions operator keyword together with an operator operator+ operator- etc. Can overload all operators except: ::. *?: 14

15 Complex with operator+ class Complex { //... public: //... Complex operator+(const Complex& c) const { Complex result; result.real = this->real + c.real; result.image = this->image + c.image; return result; //... ; int main() { Complex z(1,2), w(3,4); Complex a = z + w; a.display(); // z.operator+(w) 15

16 Global Complex Operators class Complex { double real, image; public: ; Complex(double x = 0, double y = 0) { this->real = x; this->imag = y; double getreal() const {return real; double getimage() const {return image; //... Complex operator+(const Complex& c1, const Complex& c2) { double re = c1.getreal() + c2.getreal(); double im = c1.getimage() + c2.getimage(); Complex result(re, im); return result; 16

17 friend Functions class Complex { public: Complex( ); // default Complex( double ) ; // real given Complex( double, double ) ; // both given void write( ) const; // friend functions friend Complex operator+( const Complex&, const Complex& ) ; friend Complex operator-( ( const Complex&, const Complex& ) ; friend Complex operator*( const Complex&, const Complex& ) ; friend Complex operator/( const Complex&, const Complex& ) ; private: double real; double image; ; 17

18 Implementation File // Complex + as top-level friend Complex operator+( const Complex& t, const Complex& u ) { return Complex( t.real + u.real, t.image + u.image ) ; // Complex - as top-level friend Complex operator-( ( const Complex& t, const Complex& u ) { return Complex( t.real - u.real, t.image - u.image ) ; // Complex * as top-level friend Complex operator*( const Complex& t, const Complex& u ) { return Complex( t.real * u.real - t.imag * u.image, t.imag * u.real + t.real * u.image ) ; // Complex / as top-level friend Complex operator/( const Complex& t, const Complex& u ) { double abs_sq = u.real * u.real + u.image * u.image; return Complex( (t.real( * u.real + t.image * u.image)/abs_sq, (t.image * u.real - t-real * u.image)/abs_sq); ); 18

19 Discussions Friendship (i.e., using the friend keyword) is a complex and dangerous topic for various reasons: Friendship, when applied to program design, is an escape mechanism allowing us to circumvent the principles of encapsulation and data hiding. The use of friends should therefore be minimized to situations where they can be used naturally. If friends are used, realize that friend functions or classes become implementation dependent on the classes declaring them as friends. Once the internal organization of the data of a class declaring friends changes, all its friends s must be recompiled (and possibly modified) as well. Therefore, as a rule of thumb: don't use friend functions or classes. 19

20 Global Operator Overloading Similar to friend Function Overloading, Except the Keyword friend is Omitted and Global Functions CANNOT ACCESS private Members class Complex{ //All Public Members! public: int real, image; Complex(int ip1 = 0, int ip2 = 0) :real(ip1), image(ip2){; ; void operator!(complex a) { int temp = a.real; a.real = a.image; a.image = temp; cout << "Real: " << a.real << endl; cout << "Imaginary: " << a.image << endl; main() { Complex one(1,2);!one; 20

21 Overloading of Operators Having a Variable Arity Operators Such as - Can be Unary or Binary Overloading of Such Operators Involves Creating a Unary Function (One Operand) and a Binary Function (Two Operands) Only if Both Forms are Used, They Need to be Implemented class Number{ int n; public: Number(int x = 0):n(x){ Number operator-(){n = -n; return *this; Number operator-(number ip) {n = n ip.n; ; return *this; ; main(){ Number one(1), two(2), three; one = -one; //unary operator three = one - two; //three.n = -3 21

22 Operators with Prefix and Postfix Forms Separate Functions for Each -- Prefix and Postfix -- Forms are Needed Prefix Form is Treated as an Unary Operator Postfix Form is Treated as a Binary Operator 22

23 Prefix Overloaded Function -- Example class Number{ int n; public: Number(int x):n(x){; ){; //Constructor //prefix operator -- unary Number operator++(); ; Number Number::operator++(){ n++; return *this; main(){ Number one(10); //one.n = 10 ++one; //one.n = 11 23

24 Postfix Overloaded Function -- Example Postfix Operator is Implemented as a Binary Operator with an int Argument with a Default Value of 0. When specifying an overloaded operator for the postfix form of the increment or decrement operator, the additional argument must be of type int; specifying any other type generates an error. class Number{ int n; public: Number(int x):n(x){; ){; //Constructor //postfix operator -- binary -- int argument Number operator++(int); ; Number Number::operator++(int y) {if (y!= 0) n += y; else n++; return *this; 24

25 Postfix overloaded function Example (Cont) main() { Number one(10); // one.n = 10 one++; // one.n = 11 one.operator++(2); // one.n = 13 There is no syntax for using the increment or decrement operators to pass these values other than explicit invocation, as a shown in the preceding code. A more straightforward way to implement this functionality is to overload the addition/assignment operator (+=). 25

26 Special Overloading Forms A Few Operators Require Special Treatments During Overloading Conversion Operator const Array Operator Function Call -- Parenthesis Operator Stream Insertion -- << Operator Stream Extraction -- >> Operator Pointer to Member -- -> Operator Assignment Operator new Operator delete Operator 26

27 Overloading Stream-Insertion and Stream-Extraction Operators Overloaded << and >> operators Must have left operand of types ostream &, istream & respectively It must be a non-member function (left operand not an object of the class) It must be a friend function if it accesses private data members 27

28 1 // Fig. 18.3: fig18_03.cpp 2 // Overloading the stream-insertion and 3 // stream-extraction operators. 4 #include <iostream> 5 6 using std::cout; 7 using std::cin; 8 using std::endl; 9 using std::ostream; 10 using std::istream; #include <iomanip> using std::setw; class PhoneNumber { 17 friend ostream &operator<<( ostream&, const PhoneNumber & ); 18 friend istream &operator>>( istream&, PhoneNumber & ); private: 21 char areacode[ 4 ]; // 3-digit area code and null 22 char exchange[ 4 ]; // 3-digit exchange and null 23 char line[ 5 ]; // 4-digit line and null 24 ; // Overloaded stream-insertion operator (cannot be 27 // a member function if we would like to invoke it with 28 // cout << somephonenumber;). 29 ostream &operator<<( ostream &output, const PhoneNumber &num ) 30 { 28

29 31 output << "(" << num.areacode << ") " 32 << num.exchange << "-" << num.line; 33 return output; // enables cout << a << b << c; istream &operator>>( istream &input, PhoneNumber &num ) 37 { 38 input.ignore(); // skip ( 39 input >> setw( 4 ) >> num.areacode; // input area code 40 input.ignore( 2 ); // skip ) and space 41 input >> setw( 4 ) >> num.exchange; // input exchange 42 input.ignore(); // skip dash (-) 43 input >> setw( 5 ) >> num.line; // input line 44 return input; // enables cin >> a >> b >> c; int main() 48 { 49 PhoneNumber phone; // create object phone cout << "Enter phone Number in the form (123) :\n"; // cin >> phone invokes operator>> function by 54 // issuing the call operator>>( cin, phone ). 55 cin >> phone; // cout << phone invokes operator<< function by 58 // issuing the call operator<<( cout, phone ). 59 cout << "The phone Number entered was: " << phone << endl; 60 return 0; 61 29

30 Enter phone Number in the form (123) : (800) The phone Number entered was: (800)

31 Example: Student Class class Student { public: Student(); Student( const string & id, const string & lname ); bool operator < (const Student & S2 ); Student & operator =(const = Student & S2 ); bool operator ==( ( const Student & S2 ); friend ostream & operator <<(ostream & out, const Student & S); friend istream & operator >>(istream & inp,, Student & S); private: string m_id; string m_lastname; ; 31

32 Overloading < bool operator <( const Student & S2 ) { return m_id < S2.m_ID; 32

33 Overloading = Student & operator =( const Student & S2 ) { // if assigning object to itself... if( *this == S2 ) return *this; m_id = S2.m_ID; m_lastname = S2.m_LastName; return *this; 33

Chapter 18 - C++ Operator Overloading

Chapter 18 - C++ Operator Overloading Chapter 18 - C++ Operator Overloading Outline 18.1 Introduction 18.2 Fundamentals of Operator Overloading 18.3 Restrictions on Operator Overloading 18.4 Operator Functions as Class Members vs. as friend

More information

Operator Overloading

Operator Overloading Operator Overloading Introduction Operator overloading Enabling C++ s operators to work with class objects Using traditional operators with user-defined objects Requires great care; when overloading is

More information

Friends and Overloaded Operators

Friends and Overloaded Operators Friend Function Friends and Overloaded Operators Class operations are typically implemented as member functions Some operations are better implemented as ordinary (nonmember) functions CSC 330 OO Software

More information

Operator Overloading in C++ Systems Programming

Operator Overloading in C++ Systems Programming Operator Overloading in C++ Systems Programming Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. Global Functions Overloading

More information

Friends and Overloaded Operators

Friends and Overloaded Operators Friends and Overloaded Operators Friend Function Class operations are typically implemented as member functions Some operations are better implemented as ordinary (nonmember) functions CSC 330 OO Software

More information

Introduction. W8.2 Operator Overloading

Introduction. W8.2 Operator Overloading W8.2 Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. as friend Functions Overloading Stream Insertion and Extraction

More information

W8.2 Operator Overloading

W8.2 Operator Overloading 1 W8.2 Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. as friend Functions Overloading Stream Insertion and Extraction

More information

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples. Outline Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples. 1 Arrays I Array One type of data structures. Consecutive group of memory locations

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Operator Overloading, Inheritance Lecture 6 February 10, 2005 Fundamentals of Operator Overloading 2 Use operators with objects

More information

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved Chapter 8 Operator Overloading, Friends, and References Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives Basic Operator Overloading Unary operators As member functions Friends

More information

Operator Overloading

Operator Overloading Operator Overloading Introduction Operator overloading Enabling C++ s operators to work with class objects Using traditional operators with user-defined objects Requires great care; when overloading is

More information

Operation Overloading.

Operation Overloading. Operation Overloading pm_jat@daiict.ac.in Recap: Why do we need Operator Overloading? Operator based expressions are more readable: Compare a + b * c with plus(a, times(b, c)) Recap: What is Operator Overloading?

More information

Ch 8. Operator Overloading, Friends, and References

Ch 8. Operator Overloading, Friends, and References 2014-1 Ch 8. Operator Overloading, Friends, and References May 28, 2014 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel

More information

Arrays. Week 4. Assylbek Jumagaliyev

Arrays. Week 4. Assylbek Jumagaliyev Arrays Week 4 Assylbek Jumagaliyev a.jumagaliyev@iitu.kz Introduction Arrays Structures of related data items Static entity (same size throughout program) A few types Pointer-based arrays (C-like) Arrays

More information

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that Reference Parameters There are two ways to pass arguments to functions: pass-by-value and pass-by-reference. pass-by-value A copy of the argument s value is made and passed to the called function. Changes

More information

Overloaded Operators, Functions, and Students

Overloaded Operators, Functions, and Students , Functions, and Students Division of Mathematics and Computer Science Maryville College Outline Overloading Symbols 1 Overloading Symbols 2 3 Symbol Overloading Overloading Symbols A symbol is overloaded

More information

Program construction in C++ for Scientific Computing

Program construction in C++ for Scientific Computing 1 (26) School of Engineering Sciences Program construction in C++ for Scientific Computing 2 (26) Outline 1 2 3 4 5 6 3 (26) Our Point class is a model for the vector space R 2. In this space, operations

More information

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 1 ARRAYS Arrays 2 Arrays Structures of related data items Static entity (same size

More information

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

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles Abstract Data Types (ADTs) CS 247: Software Engineering Principles ADT Design An abstract data type (ADT) is a user-defined type that bundles together: the range of values that variables of that type can

More information

CISC 2200 Data Structure Fall, C++ Review:3/3. 1 From last lecture:

CISC 2200 Data Structure Fall, C++ Review:3/3. 1 From last lecture: CISC 2200 Data Structure Fall, 2016 C++ Review:3/3 1 From last lecture: pointer type and pointer variable (stores memory addresses of a variable (of any type, local or global, automatic/static/dynamic)

More information

CS 247: Software Engineering Principles. ADT Design

CS 247: Software Engineering Principles. ADT Design CS 247: Software Engineering Principles ADT Design Readings: Eckel, Vol. 1 Ch. 7 Function Overloading & Default Arguments Ch. 12 Operator Overloading U Waterloo CS247 (Spring 2017) p.1/17 Abstract Data

More information

PIC10B/1 Winter 2014 Exam I Study Guide

PIC10B/1 Winter 2014 Exam I Study Guide PIC10B/1 Winter 2014 Exam I Study Guide Suggested Study Order: 1. Lecture Notes (Lectures 1-8 inclusive) 2. Examples/Homework 3. Textbook The midterm will test 1. Your ability to read a program and understand

More information

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 OPERATOR OVERLOADING KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2 Dynamic Memory Management

More information

Operator Overloading

Operator Overloading C++ Programming: Operator Overloading 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering Contents Operator overloading Basics on operator overloading Overloading operators as

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

Review. What is const member data? By what mechanism is const enforced? How do we initialize it? How do we initialize it?

Review. What is const member data? By what mechanism is const enforced? How do we initialize it? How do we initialize it? Review Describe pass-by-value and pass-by-reference Why do we use pass-by-reference? What does the term calling object refer to? What is a const member function? What is a const object? How do we initialize

More information

Informatik I (D-ITET) Übungsstunde 12,

Informatik I (D-ITET) Übungsstunde 12, Informatik I (D-ITET) Übungsstunde 12, 11.12.2017 Hossein Shafagh shafagh@inf.ethz.ch Self-Assessment now! Task 11.1 Finite rings a) struct int_7 { ; int value; //INV: 0

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Multiple Inheritance July 26, 2004 22.9 Multiple Inheritance 2 Multiple inheritance Derived class has several base classes Powerful,

More information

Operator overloading: extra examples

Operator overloading: extra examples Operator overloading: extra examples CS319: Scientific Computing (with C++) Niall Madden Week 8: some extra examples, to supplement what was covered in class 1 Eg 1: Points in the (x, y)-plane Overloading

More information

COMP322 - Introduction to C++

COMP322 - Introduction to C++ COMP322 - Introduction to C++ Winter 2011 Lecture 05 - I/O using the standard library & Introduction to Classes Milena Scaccia School of Computer Science McGill University February 1, 2011 Final note on

More information

More Advanced Class Concepts

More Advanced Class Concepts More Advanced Class Concepts Operator overloading Inheritance Templates PH (RH) (Roger.Henriksson@cs.lth.se) C++ Programming 2016/17 146 / 281 Operator Overloading In most programming languages some operators

More information

Module Operator Overloading and Type Conversion. Table of Contents

Module Operator Overloading and Type Conversion. Table of Contents 1 Module - 33 Operator Overloading and Type Conversion Table of Contents 1. Introduction 2. Operator Overloading 3. this pointer 4. Overloading Unary Operators 5. Overloading Binary Operators 6. Overloading

More information

Overloading Operators in C++

Overloading Operators in C++ Overloading Operators in C++ C++ allows the programmer to redefine the function of most built-in operators on a class-by-class basis the operator keyword is used to declare a function that specifies what

More information

Object oriented programming

Object oriented programming Exercises 6 Version 1.0, 21 March, 2017 Table of Contents 1. Operators overloading....................................................... 1 1.1. Example 1..............................................................

More information

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

W3101: Programming Languages C++ Ramana Isukapalli

W3101: Programming Languages C++ Ramana Isukapalli Lecture-6 Operator overloading Namespaces Standard template library vector List Map Set Casting in C++ Operator Overloading Operator overloading On two objects of the same class, can we perform typical

More information

Chapter 3. Numeric Types, Expressions, and Output

Chapter 3. Numeric Types, Expressions, and Output Chapter 3 Numeric Types, Expressions, and Output 1 Chapter 3 Topics Constants of Type int and float Evaluating Arithmetic Expressions Implicit Type Coercion and Explicit Type Conversion Calling a Value-Returning

More information

7.1 Optional Parameters

7.1 Optional Parameters Chapter 7: C++ Bells and Whistles A number of C++ features are introduced in this chapter: default parameters, const class members, and operator extensions. 7.1 Optional Parameters Purpose and Rules. Default

More information

A <Basic> C++ Course

A <Basic> C++ Course A C++ Course 5 Constructors / destructors operator overloading Julien Deantoni adapted from Jean-Paul Rigault courses This Week A little reminder Constructor / destructor Operator overloading Programmation

More information

A <Basic> C++ Course

A <Basic> C++ Course A C++ Course 5 Constructors / destructors operator overloading Julien DeAntoni adapted from Jean-Paul Rigault courses 1 2 This Week A little reminder Constructor / destructor Operator overloading

More information

Abstraction and Encapsulation. Benefits of Abstraction & Encapsulation. Concrete Types. Using Typedefs to streamline classes.

Abstraction and Encapsulation. Benefits of Abstraction & Encapsulation. Concrete Types. Using Typedefs to streamline classes. Classes II: Type Conversion,, For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Abstraction and Encapsulation Abstraction: Separation of interface from

More information

Arizona s First University. ECE 373. Operation Overloading. The Revolution Operation Will Be Televised (and, these slides will be online later today)

Arizona s First University. ECE 373. Operation Overloading. The Revolution Operation Will Be Televised (and, these slides will be online later today) Arizona s First University. ECE 373 Operation Overloading The Revolution Operation Will Be Televised (and, these slides will be online later today) Previously, on ECE373 Families of operators can be overloaded

More information

11.2. Overloading Operators

11.2. Overloading Operators 11.2 Overloading Operators Overloading Operators In the Money class, function add was used to add two objects of type Money In this section we see how to use the '+' operator to make the following code

More information

14.1. Chapter 14: static member variable. Instance and Static Members 8/23/2014. Instance and Static Members

14.1. Chapter 14: static member variable. Instance and Static Members 8/23/2014. Instance and Static Members Chapter 14: More About Classes 14.1 Instance and Static Members Instance and Static Members instance variable: a member variable in a class. Each object has its own copy. static variable: one variable

More information

Pointers and Strings Prentice Hall, Inc. All rights reserved.

Pointers and Strings Prentice Hall, Inc. All rights reserved. Pointers and Strings 1 Introduction Pointer Variable Declarations and Initialization Pointer Operators Calling Functions by Reference Using const with Pointers Selection Sort Using Pass-by-Reference 2

More information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING Dr. Shady Yehia Elmashad Outline 1. Introduction to C++ Programming 2. Comment 3. Variables and Constants 4. Basic C++ Data Types 5. Simple Program: Printing

More information

Chapter 7. Additional Control Structures

Chapter 7. Additional Control Structures Chapter 7 Additional Control Structures 1 Chapter 7 Topics Switch Statement for Multi-Way Branching Do-While Statement for Looping For Statement for Looping Using break and continue Statements 2 Chapter

More information

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator 1 A Closer Look at the / Operator Used for performing numeric calculations C++ has unary, binary, and ternary s: unary (1 operand) - binary ( operands) 13-7 ternary (3 operands) exp1? exp : exp3 / (division)

More information

Operators. Lecture 12 Section Robb T. Koether. Hampden-Sydney College. Fri, Feb 9, 2018

Operators. Lecture 12 Section Robb T. Koether. Hampden-Sydney College. Fri, Feb 9, 2018 Operators Lecture 12 Section 14.5 Robb T. Koether Hampden-Sydney College Fri, Feb 9, 2018 Robb T. Koether (Hampden-Sydney College) Operators Fri, Feb 9, 2018 1 / 21 Outline 1 Operators as Functions 2 Operator

More information

CS11 Intro C++ Spring 2018 Lecture 5

CS11 Intro C++ Spring 2018 Lecture 5 CS11 Intro C++ Spring 2018 Lecture 5 C++ Abstractions C++ provides rich capabilities for creating abstractions class Complex { double re, im; public: Complex(double re, double im);... ; Would be nice if

More information

PIC 10A Objects/Classes

PIC 10A Objects/Classes PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous

More information

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

C++ As A Better C Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan. C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2013 Fall Outline 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.5

More information

ADTs & Classes. An introduction

ADTs & Classes. An introduction ADTs & Classes An introduction Quick review of OOP Object: combination of: data structures (describe object attributes) functions (describe object behaviors) Class: C++ mechanism used to represent an object

More information

CHAPTER 3 Expressions, Functions, Output

CHAPTER 3 Expressions, Functions, Output CHAPTER 3 Expressions, Functions, Output More Data Types: Integral Number Types short, long, int (all represent integer values with no fractional part). Computer Representation of integer numbers - Number

More information

Object oriented programming

Object oriented programming Exercises 12 Version 1.0, 9 May, 2017 Table of Contents 1. Virtual destructor and example problems...................................... 1 1.1. Virtual destructor.......................................................

More information

Programming C++ Lecture 6. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor

Programming C++ Lecture 6. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor Programming C++ Lecture 6 Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Friends 2 Friends of Objects S Classes sometimes need friends. S Friends are defined outside

More information

CSc 10200! Introduction to Computing. Lecture 4-5 Edgardo Molina Fall 2013 City College of New York

CSc 10200! Introduction to Computing. Lecture 4-5 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 4-5 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 3 Assignment, Formatting, and Interactive Input

More information

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

Overloading & Polymorphism

Overloading & Polymorphism Overloading & Polymorphism Overloading is considered ad-hoc polymorphism. 1 Can define new meanings (functions) of operators for specific types. Compiler recognizes which implementation to use by signature

More information

EL2310 Scientific Programming

EL2310 Scientific Programming (pronobis@kth.se) Overview Overview Wrap Up Introduction to Object Oriented Paradigm More on and Members Operator Overloading Last time Intro to C++ Differences between C and C++ Intro to OOP Today Object

More information

2 ADT Programming User-defined abstract data types

2 ADT Programming User-defined abstract data types Preview 2 ADT Programming User-defined abstract data types user-defined data types in C++: classes constructors and destructors const accessor functions, and inline functions special initialization construct

More information

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer June 3, 2013 OOPP / C++ Lecture 9... 1/40 Const Qualifiers Operator Extensions Polymorphism Abstract Classes Linear Data Structure Demo Ordered

More information

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science Written examination Homologation C++ and Computer Organization (2DMW00) Part I: C++ - on Tuesday, November 1st 2016, 9:00h-12:00h.

More information

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects Vectors of Objects As we have mentioned earlier, you should almost always use vectors instead of arrays. If you need to keep track of persons (objects of class Person), you must decide what to store in

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Storage Classes Scope Rules Functions with Empty Parameter Lists Inline Functions References and Reference Parameters Default Arguments Unary Scope Resolution Operator Function

More information

Chapter7 Expression and Assignment Statement. Introduction

Chapter7 Expression and Assignment Statement. Introduction Chapter7 Expression and Assignment Statement Arithmetic Expressions Overloaded Operators Boolean Expressions Short-Circuit Evaluation Assignment Statements Mixed-Mode Assignment Introduction Fundamental

More information

IS0020 Program Design and Software Tools Midterm, Fall, 2004

IS0020 Program Design and Software Tools Midterm, Fall, 2004 IS0020 Program Design and Software Tools Midterm, Fall, 2004 Name: Instruction There are two parts in this test. The first part contains 22 questions worth 40 points you need to get 20 right to get the

More information

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team Question No: 1 ( Marks: 2 ) Write a declaration statement for an array of 10

More information

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types Chapter 4 - Arrays 1 4.1 Introduction 4.2 Arrays 4.3 Declaring Arrays 4.4 Examples Using Arrays 4.5 Passing Arrays to Functions 4.6 Sorting Arrays 4.7 Case Study: Computing Mean, Median and Mode Using

More information

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and

More information

Evolution of Programming Languages

Evolution of Programming Languages Evolution of Programming Languages 40's machine level raw binary 50's assembly language names for instructions and addresses very specific to each machine 60's high-level languages: Fortran, Cobol, Algol,

More information

Where do we go from here?

Where do we go from here? Where do we go from here? C++ classes and objects, with all the moving parts visible operator overloading templates, STL, standards, Java components, collections, generics language and performance comparisons

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 6 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Spring 2011 These slides are created using Deitel s slides Sharif University of Technology Outlines

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

CSS 342 Data Structures, Algorithms, and Discrete Mathematics I. Lecture 2. Yusuf Pisan

CSS 342 Data Structures, Algorithms, and Discrete Mathematics I. Lecture 2. Yusuf Pisan CSS 342 Data Structures, Algorithms, and Discrete Mathematics I Lecture 2 Yusuf Pisan Compiled helloworld yet? Overview C++ fundamentals Assignment-1 CSS Linux Cluster - submitting assignment Call by Value,

More information

Programming in C++: Assignment Week 4

Programming in C++: Assignment Week 4 Programming in C++: Assignment Week 4 Total Marks : 20 March 22, 2017 Question 1 Using friend operator function, which set of operators can be overloaded? Mark 1 a.,, , ==, = b. +, -, /, * c. =,

More information

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank 1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A. integer B 1.427E3 B. double D "Oct" C. character B -63.29 D. string F #Hashtag

More information

UEE1303(1070) S12: Object-Oriented Programming Operator Overloading and Function Overloading

UEE1303(1070) S12: Object-Oriented Programming Operator Overloading and Function Overloading UEE1303(1070) S12: Object-Oriented Programming Operator Overloading and Function Overloading What you will learn from Lab 7 In this laboratory, you will learn how to use operator overloading and function

More information

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Function Definitions - Function Prototypes - Data

More information

CS304 Object Oriented Programming Final Term

CS304 Object Oriented Programming Final Term 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes? Generalization (pg 29) Sub-typing

More information

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell

More information

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both operators and functions can be overloaded

More information

Ch. 12: Operator Overloading

Ch. 12: Operator Overloading Ch. 12: Operator Overloading Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42

More information

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology Lecture 8: Object-Oriented Programming (OOP) 1 Introduction to C++ 2 Overview Additional features compared to C: Object-oriented programming (OOP) Generic programming (template) Many other small changes

More information

Classes and Data Abstraction. Topic 5

Classes and Data Abstraction. Topic 5 Classes and Data Abstraction Topic 5 Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes The data and functions of a class

More information

Roxana Dumitrescu. C++ in Financial Mathematics

Roxana Dumitrescu. C++ in Financial Mathematics Roxana Dumitrescu C++ in Financial Mathematics What have we learnt? Arrays; relation between arrays and pointers.. Returning arrays from functions Passing arrays to functions Intoduction to classes Plan

More information

Classes. Christian Schumacher, Info1 D-MAVT 2013

Classes. Christian Schumacher, Info1 D-MAVT 2013 Classes Christian Schumacher, chschuma@inf.ethz.ch Info1 D-MAVT 2013 Object-Oriented Programming Defining and using classes Constructors & destructors Operators friend, this, const Example Student management

More information

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++ No. of Printed Pages : 3 I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination 05723. June, 2015 BCS-031 : PROGRAMMING IN C ++ Time : 3 hours Maximum Marks : 100 (Weightage 75%)

More information

Lecture 23: Pointer Arithmetic

Lecture 23: Pointer Arithmetic Lecture 23: Pointer Arithmetic Wai L. Khoo Department of Computer Science City College of New York November 29, 2011 Wai L. Khoo (CS@CCNY) Lecture 23 November 29, 2011 1 / 14 Pointer Arithmetic Pointer

More information

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) Chapter - Arrays 1.1 Introduction 2.1 Introduction.2 Arrays.3 Declaring Arrays. Examples Using Arrays.5 Passing Arrays to Functions.6 Sorting Arrays. Case Study: Computing Mean, Median and Mode Using Arrays.8

More information

Object-Oriented Design (OOD) and C++

Object-Oriented Design (OOD) and C++ Chapter 2 Object-Oriented Design (OOD) and C++ At a Glance Instructor s Manual Table of Contents Chapter Overview Chapter Objectives Instructor Notes Quick Quizzes Discussion Questions Projects to Assign

More information

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad CHAPTER 3 ARRAYS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Arrays 3. Declaring Arrays 4. Examples Using Arrays 5. Multidimensional Arrays 6. Multidimensional Arrays Examples 7. Examples Using

More information

Chapter 9. Operator Overloading. Dr Ahmed Rafat

Chapter 9. Operator Overloading. Dr Ahmed Rafat Chapter 9 Operator Overloading Overloading Operators Overloading Basics How Operators are Overloaded Arithmetic Operators Fstring Class Example Cast Operator Equality and Relational Operators Bitwise Operators

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

Introduction to C++ Programming. Adhi Harmoko S, M.Komp Introduction to C++ Programming Adhi Harmoko S, M.Komp Machine Languages, Assembly Languages, and High-level Languages Three types of programming languages Machine languages Strings of numbers giving machine

More information

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University (5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University Key Concepts 2 Object-Oriented Design Object-Oriented Programming

More information

Pointers and Strings. Adhi Harmoko S, M.Komp

Pointers and Strings. Adhi Harmoko S, M.Komp Pointers and Strings Adhi Harmoko S, M.Komp Introduction Pointers Powerful, but difficult to master Simulate call-by-reference Close relationship with arrays and strings Pointer Variable Declarations and

More information