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



Similar documents
Jzyk C++ cz 7. Jarosław Gramacki Instytut Informatyki i Elektroniki

C++FA 5.1 PRACTICE MID-TERM EXAM

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) {

1. Polymorphism in C++...2

C++ Overloading, Constructors, Assignment operator

C++ INTERVIEW QUESTIONS

Advanced Data Structures

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

Constructor, Destructor, Accessibility and Virtual Functions

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

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

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

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

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

El Dorado Union High School District Educational Services

The C Programming Language course syllabus associate level

Java Interview Questions and Answers

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

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

Practical Programming Methodology. Michael Buro. Class Inheritance (CMPUT-201)

Compile-time type versus run-time type. Consider the parameter to this function:

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

Comp151. Definitions & Declarations

16 Collection Classes

C++ Programming Language

13 Classes & Objects with Constructors/Destructors

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

Object Oriented Software Design II

Ch 7-1. Object-Oriented Programming and Classes

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang

Curriculum Map. Discipline: Computer Science Course: C++

Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance

Object Oriented Software Design II

CIS 190: C/C++ Programming. Polymorphism

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

An Internet Course in Software Development with C++ for Engineering Students

Introduction to Programming Block Tutorial C/C++

CEC225 COURSE COMPACT

Glossary of Object Oriented Terms

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

Object Oriented Software Design II

CS 111 Classes I 1. Software Organization View to this point:

Part I. Multiple Choice Questions (2 points each):

CSE 1020 Introduction to Computer Science I A sample nal exam

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

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

EP241 Computer Programming

Class 16: Function Parameters and Polymorphism

Course notes Standard C++ programming

CISC 181 Project 3 Designing Classes for Bank Accounts

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

Object-Oriented Programming Lecture 2: Classes and Objects

N3458: Simple Database Integration in C++11

Konzepte objektorientierter Programmierung

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES CONSTRUCTORS AND DESTRUCTORS

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)

OpenCL Static C++ Kernel Language Extension

Java (12 Weeks) Introduction to Java Programming Language

Description of Class Mutation Mutation Operators for Java

Passing 1D arrays to functions.

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

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

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

Java CPD (I) Frans Coenen Department of Computer Science

Brent A. Perdue. July 15, 2009

MAHALAKSHMI ENGINEERING COLLEGE B TIRUCHIRAPALLI

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

History OOP languages Year Language 1967 Simula Smalltalk

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

Computer Science 1 CSci 1100 Lecture 3 Python Functions

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

Help on the Embedded Software Block

Basics of C++ and object orientation in OpenFOAM

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Pluggable Type Systems. Gilad Bracha

Java Programming Language

Object Oriented Programming With C++(10CS36) Question Bank. UNIT 1: Introduction to 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.

CS193j, Stanford Handout #10 OOP 3

AP Computer Science Java Subset

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

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

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

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

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

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

Chapter 5 Functions. Introducing Functions

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

C++FA 3.1 OPTIMIZING C++

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

Binary storage of graphs and related data

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

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

J a v a Quiz (Unit 3, Test 0 Practice)

Objectif. Participant. Prérequis. Remarque. Programme. C# 3.0 Programming in the.net Framework. 1. Introduction to the.

Conditions & Boolean Expressions

Transcription:

Polymorphism Problems with switch statement Programmer may forget to test all possible cases in a switch. Tracking this down can be time consuming and error prone Solution - use virtual functions (polymorphism) Virtual functions and polymorphic programming can eliminate the need for switch Design and implement systems that are more easily extensible Programs written to generically process objects of all existing classes in a hierarchy Polymorphism Ability for objects of different classes to respond differently to the same function call Base-class pointer (or reference) calls a virtual function - C++ chooses the correct overridden function in object Dynamic binding (late binding ) as opposite to early (static) binding Object's type not needed when compiling virtual functions Accommodate new classes that have been added after compilation Important for ISV s (Independent Software Vendors) who do not wish to reveal source code to their customers Virtual functions The keyword virtual is a function specifier that provides a mechanism to dynamically select at runtime the appropriate member function from among base and derived class functions (polymorphism=many forms ). A base-class pointer (reference) to a derived class object will call the correct draw function If a derived class does not define a virtual function it is inherited from the base class There are two types of virtual functions: virtual double area(); // normal virtual virtual double area() =0; // pure virtual

An example class Instrument { void play() const {cout<< "Instrument::play"<<endl; char* what() const {return"instrument"; class Wind : public Instrument { void play() const {cout<< Wind::play"<<endl; char* what() const {return Wind"; void go(instrument& i) { i.play(); // binding during compilation... Instrument instrument; Wind wind; go(instrument); // play from class Instrument not surprising go(wind); // play from class Instrument why? An example Now using virtual function class Instrument { virtual void play() const {cout<< "Instrument::graj"<<endl; virtual char* what() const {return"instrument"; class Wind : public Instrument { void play() const {cout<< Wind::play"<<endl; char* what() const {return Wind"; void go(instrument& i) { i.play(); Instrument instrument; Wind ourwind; Instrument *demo; demo= &instrument; demo->play(); demo = &ourwind; demo->play(); Instrument instrument; Wind ourwind; Instrument &demo1 = instrument; demo1.play(); Instrument &demo2 = ourwind; demo2.play(); An example Using pointers // play from class Instrument // play from class Wind Using reference // play from class Instrument // play from class Wind

VTABLE Small problem Access specifier from class for which pointer is defined is used class basic { virtual void fun( ); class derived : public basic { virtual void fun( ); basic *pointer1; derived *pointer2; pointer1->fun( ); // O.K. pointer2->fun( ); //? Collection class Point {... virtual void draw(); class Circle: public Point {... virtual void draw(); class Collection { protected: Point ** arr; int size; Collection(int n); void draw() void insert (Point *p, int i); void Collection:draw() { for(int i=0;i<size;i++) if (arr[i]!= 0) arr[i] -> draw();

Abstract classes A pure virtual function is one whose body is undefined. virtual void printname() = 0; derived classes must implement the pure virtual functions (else they will be abstract too!) A pure virtual function is used to defer the implementation decision of the function. A class that has at least one pure virtual function is called an abstract class (normal classes are sometimes called concrete classes). Abstraction is just a design mechanism - a way of deferring design decisions. Abstract classes Typically: the base class in a hierarchy of classes is an abstract class. (Its only there to help the designer start the hierarchy - an abstract class might often contain some data declarations and maybe some methods, but it is never intended to actually be instantiated) An abstract class cannot be used to declare objects (cannot be instantiated). An abstract class can be used to declare pointers that can access objects derived from the abstract base class. Abstract classes //definition of the abstract base class class TwoD { //this is an abstract class virtual double area() const { return 0.0; //pure virtual member function virtual void printname()const = 0; By having any pure virtual member function, this class is declared as abstract.

Virtual - constructors and destructors? Constructors are always dynamic (don t need virtual.) Destructors should be declared virtual (if you delete a derived class through a base pointer.) There can be significant problems if you don t declare destructors virtual and you try to delete through the base pointer. (The wrong memory can be freed up if your classes use malloc or new etc ) We will return to this issue. Overloading & virtual functions Virtual functions provide another way to overload names, and hence another way to provide a form of polymorphism. The same types Binding Overloaded functions never Compilation time Virtual functions always runtime Summary A pure virtual function is a function whose body is undefined. A class having a pure virtual member function is an abstract class. An abstract base class defines the interface for its derived classes but cannot itself be used to declare objects. Polymorphism - the ability for objects of different classes related by inheritance to respond differently to the same message (function call). We can use more elaborate combinations of the access modifier when deriving classes from base classes.

Abstract class class Shape { virtual double area() const { return 0.0; virtual double volume() const { return 0.0; // pure virtual functions overridden in derived classes virtual void printshapename() const = 0; virtual void print() const = 0; Class Point class Point : public Shape { Point( int = 0, int = 0 ); // default constructor void setpoint( int, int ); int getx() const { return x; int gety() const { return y; virtual void printshapename() const { cout << "Point: "; virtual void print() const; private: int x, y; // x and y coordinates of Point Point::Point( int a, int b ) { setpoint( a, b ); void Point::setPoint( int a, int b ) { x = a; y = b; void Point::print() const { cout << '[' << x << ", " << y << ']';

Class Circle class Circle : public Point { Circle( double r = 0.0, int x = 0, int y = 0 ); void setradius( double ); double getradius() const; virtual double area() const; virtual void printshapename() const { cout << "Circle: "; virtual void print() const; private: double radius; // radius of Circle Circle::Circle( double r, int a, int b ) : Point( a, b ) // call base-class constructor {setradius( r ); void Circle::setRadius( double r ) { radius = r > 0? r : 0; double Circle::getRadius() const { return radius; double Circle::area() const { return 3.14159 * radius * radius; void Circle::print() const { Point::print(); cout << "; Radius = " << radius; Class Cylinder class Cylinder : public Circle { // default constructor Cylinder( double h = 0.0, double r = 0.0, int x = 0, int y = 0 ); void setheight( double ); double getheight(); virtual double area() const; virtual double volume() const; virtual void printshapename() const { cout << "Cylinder: "; virtual void print() const; private: double height; // height of Cylinder

Cylinder::Cylinder( double h, double r, int x, int y ) : Circle( r, x, y ) // call base-class constructor { setheight( h ); void Cylinder::setHeight( double h ) { height = h > 0? h : 0; double Cylinder::getHeight() { return height; double Cylinder::area() const { // surface area of Cylinder return 2 * Circle::area() + 2 * 3.14159 * getradius() * height; double Cylinder::volume() const { return Circle::area() * height; void Cylinder::print() const { Circle::print(); cout << "; Height = " << height;