OBJECT ORIENTED PROGRAMMING USING C++

Similar documents
CS3157: Advanced Programming. Outline

Polymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

Advanced C++ Programming Workshop (With C++11, C++14, C++17) & Design Patterns

Increases Program Structure which results in greater reliability. Polymorphism

C++ Programming: Polymorphism

W3101: Programming Languages C++ Ramana Isukapalli

Tokens, Expressions and Control Structures

CS105 C++ Lecture 7. More on Classes, Inheritance

Laboratorio di Tecnologie dell'informazione

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.

Polymorphism. Zimmer CSCI 330

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini

ECE 3574: Dynamic Polymorphism using Inheritance

More Advanced Class Concepts

CS11 Advanced C++ Fall Lecture 7

C++ Important Questions with Answers

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

Instantiation of Template class

Inclusion Polymorphism

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

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

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

Variables. Data Types.

Where do we stand on inheritance?

C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete.

Overloaded Operators, Functions, and Students

These new operators are intended to remove some of the holes in the C type system introduced by the old C-style casts.

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Fast Introduction to Object Oriented Programming and C++

Welcome to Teach Yourself Acknowledgments Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p.

Introduction to C++ Systems Programming

2 ADT Programming User-defined abstract data types

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Object-Oriented Principles and Practice / C++

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

The Four Polymorphisms in C++ Subtype Polymorphism (Runtime Polymorphism) Polymorphism in C

The Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured

Basic Types, Variables, Literals, Constants

Ch. 12: Operator Overloading

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

Introduction to RTTI. Jonathan Hoyle Eastman Kodak 11/30/00

Polymorphism Part 1 1

C++ Inheritance II, Casting

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types

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

Dr. Md. Humayun Kabir CSE Department, BUET

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Short Notes of CS201

1c) (iv) and (v) OR (v) only (hindsight showed that the question was more ambiguous than intended)

C++ Functions. Procedural-based Programming. what s a functions

CPSC 427: Object-Oriented Programming

(7-2) Operator Overloading D & D Chapter 10. Instructor - Andrew S. O Fallon CptS 122 (February 23, 2018) Washington State University

CS201 - Introduction to Programming Glossary By

Chapter 2. Procedural Programming

Chapter 3 Function Overloading

Introduction to Programming Using Java (98-388)

Absolute C++ Walter Savitch

Interview Questions of C++

C++ Crash Kurs. Polymorphism. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

15: Polymorphism & Virtual Functions

Operators. The Arrow Operator. The sizeof Operator

Introduction to Programming

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

TPF Users Group Spring 2005

Inheritance & Polymorphism. Object-Oriented Programming Spring 2015

CPSC 427: Object-Oriented Programming

IS 0020 Program Design and Software Tools

aggregate data types member functions cis15 advanced programming techniques, using c++ lecture # II.1

Programming, numerics and optimization

Implementing Abstract Data Types (ADT) using Classes

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

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Strict Inheritance. Object-Oriented Programming Winter

COMP322 - Introduction to C++ Lecture 09 - Inheritance continued

Object-Oriented Programming, Iouliia Skliarova

Overload Resolution. Ansel Sermersheim & Barbara Geller ACCU / C++ June 2018

CS304 Object Oriented Programming Final Term

G52CPP C++ Programming Lecture 17

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

Inheritance and aggregation

Evolution of Programming Languages

Input/output. Remember std::ostream? std::istream std::ostream. std::ostream cin std::istream. namespace std { class ostream { /*...

Ch. 3: The C in C++ - Continued -

ADTs & Classes. An introduction

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

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

Strict Inheritance. Object-Oriented Programming Spring 2008

G52CPP C++ Programming Lecture 13

CPSC 427: Object-Oriented Programming

Module Operator Overloading and Type Conversion. Table of Contents

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.

C++ Inheritance II, Casting

Overview. Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

SFU CMPT Topic: Class Templates

Chapter 5. Object- Oriented Programming Part I

Transcription:

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 Different definitions must be distinguished by their signatures (otherwise which to call is ambiguous) Reminder: signature is the operator/function name and the ordered list of its argument types E.g., add(int,long) and add(long,int) have different signatures E.g., add(const Base &) and add(const Derived &) have different signatures, even if Derived is-a Base Most specific match is used to select which one to call

Overloading vs. Overriding Overriding a base class method is similar to overloading But definitions are distinguished by their scopes rather than by their signatures C++ can distinguish method definitions according to either static or dynamic type Depends on whether a method is virtual or not Depends on whether called via a reference or pointer vs. directly on an object Depends on whether the call states the scope explicitly (e.g., Foo::baz();)

class A { public: int add(int i, int j); ; // not allowed, would be // ambiguous with above // long add(int m, int n); // Ok, different signature long add(long m, long n); int main (int argc, char **argv) { int a = 7; int b = 8; int c = add(a, b); return 0; Function Overloading Calls to overloaded functions and operators are resolved by Finding all possible matches based on passed arguments May involve type promotion May involve instantiating templates Finding the best match among those possible matches Signature does not include the return type Which might not help even if it did, i.e., calls may ignore result So, overloading can t be resolved by return type alone Compiler generates an error if the call can t be resolved

class A { friend ostream &operator<< (ostream &, const A &); private: int m_a; ; ostream &operator<< (ostream &out, const A &a) { out << "A::m_a = " << a.m_a; return out; int main () { A a; cout << a << endl; return 0; Operator Overloading Similar to function overloading Resolved by signature Best match is used But the list of operators and the arity of each is fixed Can t invent operators Must use same number of arguments as for built-in types (except for operator()) Some operators are off limits :: (scope). (dot)?: (conditional) sizeof typeid (RTTI) type casting operators

Operator Symmetry, Precedence class Complex { public: // constructor from real and // imaginary parts Complex (int r, int i); // addition Complex operator+ (const Complex &); // multiplication Complex operator* (const Complex &); // exponentiation Complex operator^ (const Complex &); private: int real_; int imaginary_; ; In general, make operators symmetric Don t mix base and derived types in their parameter lists Operators always obey the same precedence rules (Prata pp. 1058) Can lead to some unexpected mistakes E.g., what s wrong with this Complex number expression? a + b * c ^ 2

Member/Non-Member Overloading class A { friend bool operator< (const A &lhs, const A &rhs); public: bool operator==(const A &a) const; private: int m_a; ; // member operator bool A::operator==(const A &a) const { // note: object itself is // the first argument, can be const return m_a == a.m_a; // non-member operator bool operator< (const A &lhs, const A &rhs) { return lhs.m_a < rhs.m_a; Remember a this pointer is passed to any non-static member function So, for member functions and operators the object itself does not appear in the argument list For non-member functions and operators all parameters appear So, the rule about operator arity is obeyed in code on left Both < and == are binary operators Can you see what needs to be added to both of these operators? Non-member operators are useful when working with classes you wrote and classes you didn t write E.g., ostream << and istream >> Non-member operators are also useful to preserve symmetry May avoid unexpected type conversions, especially up an inheritance hierarchy

Type Cast Operators (and typedef) int main (int, const char * argv[]) { // cast away constness char *p = const_cast<char*>(argv[0]) // convert to smaller type int i = 50; char c = static_cast<char>(i); // downcast a pointer (returns // 0 if *bptr isn t a Derived) Base * bptr = new Derived; Derived * dptr = dynamic_cast<derived*>(bptr); // reinterpret a pointer typedef unsigned long ulong; ulong cookie = reinterpret_cast<ulong>(p); Four type cast operators in C++ Only use these when you must You cannot overload them Take a type parameter (generic) To get a mutable interface from a const one, use const_cast To force a static type conversion that s known to be safe at runtime use static_cast To force a dynamic type conversion that s known to be safe at runtime use dynamic_cast To reinterpret a type as another type (strongest form of casting) use reinterpret_cast To alias a type, use typedef

Summary: Tips on Overloading Use virtual overriding when you want to substitute different subtypes polymorphically E.g., move() in derived and base classes Use overloading when you want to provide related interfaces to similar abstractions E.g., migrate(bird &) vs. migrate(elephant &) Use different names when the abstractions differ E.g., fly() versus walk()