C++ Training Datascope Lawrence D’Antonio Lecture 6 An Overview of C++: What is Polymorphism? - Coercion.

Slides:



Advertisements
Similar presentations
The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
Advertisements

OOP Class Lawrence D’Antonio Lecture 4 An Overview of C++, Part 2.
C++ Training Datascope Lawrence D’Antonio Lecture 3 An Overview of C++
. Copying, casting, and more. Example: MyString u Lets put our knowledge of C++ classes to use u Define a class to represent a string u Replace all the.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
OOP Spring 2007 – Recitation 21 Object Oriented Programming Spring 2007 Recitation 2.
2 Objectives You should be able to describe: Operator Functions Two Useful Alternatives – operator() and operator[] Data Type Conversions Class Inheritance.
C++ Training Datascope Lawrence D’Antonio Lecture 1 Quiz 1.
1 Type Type system for a programming language = –set of types AND – rules that specify how a typed program is allowed to behave Why? –to generate better.
C++ Training Datascope Lawrence D’Antonio Lecture 5 An Overview of C++: What is Polymorphism? - Overloading.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
Chapter 4 Inheritance Bernard Chen Spring Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism.
Ch 7. Operator Overloading Timothy Budd. Ch 7. Operator Overloading2 Introduction Almost all operators in C++ can be overloaded with new meanings. Operators.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
CSE 333 – SECTION 4. Overview Pointers vs. references Const Classes, constructors, new, delete, etc. More operator overloading.
CS (CCN 27241) Software Engineering for Scientific Computing Lecture 5: C++ Key Concepts.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Type Equivalence Rules Ada –Strict name equivalence except for almost everything Unique array constructors give rise to unique types Subtypes can create.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Introduction to Classes in C++
Operator Overloading Version 1.0. Objectives At the end of this lesson, students should be able to: Write programs that correctly overload operators Describe.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Chapter 9 Questions 1. What are the difference between constructors and member functions? 2. Design and implement a simple class as you want, with constructors.
Object Management. Constructors –Compiler-generated –The Initializer List –Copy Constructors –Single-arg (conversion ctors) The Assignment Operator.
Class and Structure. 2 Structure Declare using the keyword struct purpose is to group data Default visibility mode is public A struct doesn't have a constructor.
Operator Overloading Week 5.
Functions Sujana Jyothi C++ Workshop Day 2. Functions 3 Parameter transmission modes pass by value (default) pass by reference (&) pass by const reference.
Csi2172 class 5 Midterm: June 12. constructor Special method used to create objects of the class Never has a return type. Is called automatically upon.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 RAD due Friday in your Wiki. Presentations week 6 – next week. Schedule on next slide. Today: –Operator.
Functions. Introduction A sequence of statements that perform some related and useful processing. Functions have 3 components :- ( ) Note :- Declaration.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Project Wikis will be made public tonight. Presentations week 6 – next week. Slack Chat invites sent.
Inheritance and Composition Reusing the code and functionality Unit - 04.
C++ for Java Programmers Chapter 2. Fundamental Daty Types Timothy Budd.
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
Overview of C++ Polymorphism
Classes - Part II (revisited) n Constant objects and member functions n Definition Form of Member Functions n friend functions and friend classes n Constructors.
Recap Stale Pointers and Double Delete Reference Variables Reference Type vs Pointer Type Structures Pointers to Structures Exogenous vs Indigenous Data.
Functions Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd September 2006.
Class Inheritance Inheritance as an is-a relationship Public derive one class from another Protected access Initializer lists in constructor Upcasting.
ENEE150 – 0102 ANDREW GOFFIN Abstract Data Types.
CS 342: C++ Overloading Copyright © 2004 Dept. of Computer Science and Engineering, Washington University Overview of C++ Overloading Overloading occurs.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Object-Oriented Programming Review 1. Object-Oriented Programming Object-Oriented Programming languages vary but generally all support the following features:
Operator Overloading.
Chapter 2 Objects and Classes
7. Inheritance and Polymorphism
Object-Oriented Programming (OOP) Lecture No. 45
Operator overloading Conversions friend inline
Andy Wang Object Oriented Programming in C++ COP 3330
Operator overloading Conversions friend inline
Review: Two Programming Paradigms
Operator overloading Conversions friend inline
Operator Overloading CSCE 121 J. Michael Moore
CS212: Object Oriented Analysis and Design
Initialization List.
Overview of C++ Overloading
COP 3330 Object-oriented Programming in C++
Overview of C++ Polymorphism
Java Programming Language
ENERGY 211 / CME 211 Lecture 18 October 31, 2008.
Templates CMSC 202, Version 4/02.
Operator Overloading CSCE 121 Based on Slides created by Carlos Soto.
Chapter 11 Classes.
Presentation transcript:

C++ Training Datascope Lawrence D’Antonio Lecture 6 An Overview of C++: What is Polymorphism? - Coercion

What is polymorphism?  Different types of objects respond to the same message and use the appropriate method. Polymorphism Universal Ad-hoc Parametric Subtype Overloading Coercion

  A coercion is an implicit type conversion. This allows the programmer to omit a type cast.   There are three types of coercions:   Compiler defined (such as promotions, derived  base)   Constructor   User defined

Compiler defined coercions   Simple example double x; x = 2; //2 promoted to double

Function call coercions void foo(double x) { //... } //foo() can be called with any type that can be //converted to double foo((short) 4); foo(‘a’); foo(3L); foo(2.3F);

Is this legal? #include void f(char a, int b) { std::cout << a << b << '\n'; } void f(int a, char b) { std::cout << a << b << '\n'; } main() { f('a','b'); return 0; }

Not legal, it’s ambiguous.

Coercion vs. Overloading example 3 + 4; ; ; ; How does this work?

Explanations of example   Four overloaded versions of operator +   Two overloaded versions of operator +, one for integers, the other for doubles. The middle two calls in the example would use coercion.   One version of operator +, for doubles. The first three calls in the example would use coercion.

Derived to Base Conversion   C++ will implicitly convert a pointer or reference to a derived class to a pointer or reference to the base class. This is because the derived class has a copy of the base class inside it.   A pointer to the base class cannot be converted to a pointer to the derived class.

Is this legal? class A {}; class B: public A {}; class C: protected A {}; class D: private A {}; main() { A *pa = new B; pa = new C; pa = new D; return 0; }

pa = new B; //Legal, B is an A pa = new C; //Illegal, C is not an A pa = new D; //Illegal, D is not an A In the last two cases, the base class is inaccessible.

Is this legal? class A {}; class C: protected A { public: void foo() { A *pa = this; } }; class D: private A { public: void foo() { A *pa = this; } }; main() { C c; c.foo(); D d; d.foo(); return 0; }

Yes, it’s legal. Protected and private inheritance exemplify a has-a relationship, rather than an is-a relationship. Member functions are allowed to convert pointer to derived into pointer to base.

Pointer to Member Conversions   What is the relationship between a pointer to member of a base class and a derived class?

Is this legal? struct A { int a; }; struct B: public A { int a; }; main() { A a; B b; int A::*pa = &B::a; int B::*pb = &A::a; return 0; }

Complicated. int A::*pa = &B::a; is illegal. Can’t convert pointer to derived member to a pointer to base member. int B::*pb = &A::a; Is legal. Can convert pointer to base member to a pointer to derived member.

Conversion Constructors   Constructors that take a single argument can be thought of as a type conversion. struct X { X(int); };   So that any code that expects an object of class X can be passed an int that will then be converted to an X.

Is this legal? struct X { X(int){} }; void f(const X &) {} void g(int) {} void g(X) {} main() { f(3); g(4); g(X(5)); return 0; }

f(3); //Legal, you can create a temp //object X(3), which is passed to //f() g(4); //Legal, calls g(int) g(X(5)); //Legal, calls g(X)

Is this legal? struct X { X(int){} }; void f(X &) {} void g(int) {} void g(X) {} main() { int a = 2; f(3); f(a); g(4); g(X(5)); return 0; }

f(3); //Not legal, can’t use temp X object to initialize an X & f(a); //Not legal, can’t use temp X object to initialize an X & g(4); //Legal, as before g(X(5)); //Legal, as before

Is this legal? struct X { X(int){} }; struct Y { Y(X) {} }; void f(Y) {} main() { f(3); return 0; }

Not legal. Basically, only one level conversions are allowed. Not allowed to convert int to X to Y.

Is this legal? struct X { X(int){} }; void f(X) {} void g(int) {} void g(X) {} main() { int a = 2; f(3); f(a); g(4); g(X(5)); return 0; }

f(3); //Legal, temp X is passed by value f(a); //Legal, temp X is passed by value g(4); //Legal, as before g(X(5)); //Legal, as before

Is this legal? class X { public: X() { std::cout << "Hello\n"; } void foo() { std::cout << "In X::foo()\n"; } }; class Y { X ex; public: Y(X x): ex(x) { std::cout << "World\n"; } void foo() { ex.foo(); } void foo(X x) { x.foo(); } void foo(Y y) { y.foo(); } }; main() { Y y(X()); y.foo(y); return 0; }

Not legal! The problem is y.foo(y). foo is not a member of y, which is of non- class type Y ()(X (*)()). This can be fixed with Y y = X();

Explicit Constructors   Single argument constructors (or constructors that can be called with a single argument) can lead to unexpected consequences.

class X { int x; public: X(int a = 0):x(a) {} }; main() { X ptr_x = 0; //...

That was bad!   The programmer probably meant X *ptr_x = 0;   But the compiler performed the conversion X ptr_x = X(0);

Solution class X { int x; public: explicit X(int a = 0):x(a) {} }; main() { X ptr_x = 0; //...

The compiler will flag the following as an error: X ptr_x = 0; This code implicitly uses the constructor X(int) In order to use this constructor, one must explicitly call the constructor. X ptr_x = X(0);

Constructor Rule   Any single argument constructor should be declared explicit.

Conversion operators   A user defined operator that converts a user defined object into another type.   The destination type may be a built-in or user defined type.

Example class Fraction { int numerator, denominator; public: Fraction(int n = 0, int d = 1): numerator(n), denominator(d) {} //... operator double() const { return static_cast (numerator)/denominator; } };

Usage Fraction f(3,4); double d = f; // d is 0.75 double x = f + 2;

Is this legal? Fraction f(1,2), g(1,3); Fraction h; h = f + g;

Hard to tell! h = f + g; This is legal if there is an overloaded operator + that takes Fraction operands. This is also legal if, in the unlikely case, there was a ctor Fraction(double).

Perils of conversion template class Ptr { T *p; public: //... operator bool() const { return p ? true : false; } }; Ptr ptr1; Ptr ptr2; if (ptr1 == ptr2) {/...}

The comparison ptr1 == ptr2 is valid because the Ptr s are converted into bools and then compared. So Apples and Oranges can be compared! If operator == were overloaded for type Ptr, then that version would be called.

Is this legal? string filename = “data.txt”; ifstream in_file(filename);

Not legal! ifstream constructor expects a const char * argument. Legal version: ifstream in_file(filename.c_str());

Is this legal? //Let’s define a conversion operator for // string class operator const char*(const string &s) { return s.c_str(); } string filename = “data.txt”; ifstream in_file(filename);

Not legal! Conversion operators can only be member functions.

C++ is weakly typed class Tupid { public: template operator X { return X(); } };

This means that objects of class T can be converted into an object of any (yes, any) type that has a default constructor. Tupid t; int a = t; string s = t; vector v = t;

Breaking encapsulation class A { public: void foo() {}; } ; class D: private A { public: A *foo() { A *pa = this; return pa; } }; main() { D d; A *pa = d.foo(); pa->foo(); //Calls A::foo //...

Breaking encapsulation 2 class A { int a; public: int *foo() { return &a; } }; main() { A a; int *p = a.foo(); *p = 12;

Breaking encapsulation 3 class A { private: int a; }; class B: public A {}; main() { A a; B b; int B::*pb = &A::a; b.*pb = 5; return 0; }

Not legal. A::a accesses private data