Advanced Program Design with C++

Slides:



Advertisements
Similar presentations
Chapter 15 Polymorphism and Virtual Functions. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Virtual Function.
Advertisements

Copyright © 2002 Pearson Education, Inc. Slide 1.
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
CPA: C++ Polymorphism Copyright © 2007 Mohamed Iqbal Pallipurath Overview of C++ Polymorphism Two main kinds of types in C++: native and user-defined –User-defined.
Virtual Functions Junaed Sattar November 10, 2008 Lecture 10.
1 Data Structures - CSCI 102 CS102 C++ Polymorphism Prof Tejada.
Inheritance in C++ CS-1030 Dr. Mark L. Hornick.
1 Classes- Inheritance Multiple Inheritance It is possible to derive a new class from more than one base class. This is called Multiple Inheritance. Under.
Polymorphism &Virtual Functions
Polymorphism &Virtual Functions 1. Polymorphism in C++ 2 types ▫Compile time polymorphism  Uses static or early binding  Example: Function and operator.
Chapter 15 Polymorphism and Virtual Functions. Learning Objectives Virtual Function Basics – Late binding – Implementing virtual functions – When to use.
Slide 1 Polymorphism and Virtual Functions. Slide 2 Learning Objectives  Virtual Function Basics  Late binding  Implementing virtual functions  When.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Inheritance Joe Meehean. Object Oriented Programming Objects state (data) behavior (methods) identity (allocation of memory) Class objects definition.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Polymorphism and Virtual Functions. Motivation Polymorphism is one of the fundamental mechanisms offered by OOP, and it is directly related to inheritance.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Polymorphism, Abstraction and Virtual Functions. In this slide, we introduce virtual functions and two complex and powerful uses for derived classes that.
Chapter 10 Inheritance and Polymorphism
CSCI-383 Object-Oriented Programming & Design Lecture 18.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 3 is due Sunday, the 8 th at 7pm. Problems with assn 3? Discuss at your team meeting tonight.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
CSC241 Object-Oriented Programming (OOP) Lecture No. 17.
Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.
CSC 143 O 1 CSC 143 Inheritance and Object Oriented Design.
Abstract classes only used as base class from which other classes can be inherit cannot be used to instantiate any objects are incomplete Classes that.
Advanced Program Design with C++
Pointer to an Object Can define a pointer to an object:
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Procedural and Object-Oriented Programming
Modern Programming Tools And Techniques-I
Virtual Function and Polymorphism
CMSC 202 Polymorphism.
Polymorphism and Virtual Functions
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
7. Inheritance and Polymorphism
Polymorphism &Virtual Functions
Advanced Program Design with C++
Object-Oriented Programming & Design Lecture 18 Martin van Bommel
Polymorphism.
classes and objects review
Introduction to Classes
Polymorphism & Virtual Functions
CS250 Introduction to Computer Science II
Classes in C++ C++ originally called "C with classes":
Object Oriented Programming
Polymorphism Lec
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Introduction to Classes
Learning Objectives Inheritance Virtual Function.
Classes in C++ C++ originally called "C with classes":
Virtual Functions Department of CSE, BUET Chapter 10.
Polymorphism CT1513.
Inheritance Virtual Functions, Dynamic Binding, and Polymorphism
Programming II Polymorphism A.AlOsaimi.
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
Polymorphism CMSC 202, Version 4/02.
Object-Oriented Programming: Polymorphism
Inheritance: Polymorphism and Virtual Functions
Inheritance Virtual Functions, Dynamic Binding, and Polymorphism
Today’s Objectives 10-Jul-2006 Announcements Quiz #3
Overview of C++ Polymorphism
Classes: Arrays group many objects of the same type (in order)
Computer Science II for Majors
Presentation transcript:

Advanced Program Design with C++ COMP 345 - Advanced Program Design with C++ Advanced Program Design with C++ Virtual functions Abstract classes Slicing problem Function pointers Polymorphism Virtual functions tables Joey Paquet, 2007-2014

Polymorphism Virtual Polymorphism COMP 345 - Advanced Program Design with C++ Polymorphism Polymorphism Associating many meanings to one function. Virtual functions provide this capability. Fundamental principle of object-oriented programming. Virtual Existing in "essence" though not in fact. Virtual functions. Virtual (abstract) classes. Joey Paquet, 2007-2014

Best explained by example: Classes for several kinds of figures COMP 345 - Advanced Program Design with C++ Polymorphism Best explained by example: Classes for several kinds of figures Rectangles, circles, etc. Each figure is an object of a different class Each have different data elements and formulas to compute them Rectangle data: name, area, perimeter, height, width Circle data: name, area, perimeter, radius All derive from one parent-class: CShape Requires a method getArea() Different formula to compute different figures’ area, requires different implementation for each kind of figure Joey Paquet, 2007-2014

Each class needs a different getArea() function COMP 345 - Advanced Program Design with C++ Polymorphism Each class needs a different getArea() function Can define a member getArea() in each class, so: Nothing new here yet… CRectangle r; CCircle c; r.getArea(); //Calls Rectangle’s getArea c.getArea(); //Calls Circle’s getArea Joey Paquet, 2007-2014

COMP 345 - Advanced Program Design with C++ Polymorphism Problem! Parent class Figure may contain functions that applies to all kinds of figures. Consider: print() : prints out all characteristics common to all kinds of figures Fine for getName(), as it has common behavior. However, getArea()has subclass-specific behavior Complications! Which getArea() function to call? From which class? Here, a function that exposes common behavior uses another function that exposes subclass-specific behavior. May hardcode a function that calls the right getArea() depending on which subclass the figure in question is. Need a mechanism to call subclass-specific behavior automatically Joey Paquet, 2007-2014

COMP 345 - Advanced Program Design with C++ Polymorphism Problem! Consider a new kind of figure later coming along: CTriangle class derived from CShape class Function print() inherited from CShape Will it work for triangles? It uses getArea(), which is different for each subclass of figure It will use CShape::getArea(), which was not made to work for triangles We want the inherited function center() to use the function Triangle::getArea() and not the function CShape::getArea() But class CTriangle wasn’t even written when CShape::print() was written. It does not “know” about triangles. If print() is hard-coded to call the right getArea() depending on the type of CShape, we need to change the implementation of print()every time we add a new subclass of Cshape. Again, we need a mechanism to automatically call subtype-specific behavior. Joey Paquet, 2007-2014

Polymorphism void displayCShapeDynamicCastDemo(CShape& shape) { COMP 345 - Advanced Program Design with C++ Polymorphism void displayCShapeDynamicCastDemo(CShape& shape) { CShape* p = &shape; CCircle* p1 = dynamic_cast<CCircle*>(p); CRectangle* p2 = dynamic_cast<CRectangle*>(p); CTriangle* p3 = dynamic_cast<CTriangle*>(p); if (p1 != NULL){ cout << "Circle's area is " << p1->getArea() << endl; cout << "Circle's radius is " << p1->getRadius() << endl; } if (p2 != NULL){ cout << "Rectangle's area is " << p2->getArea() << endl; cout << "Rectangle's width is " << p2->getWidth() << endl; cout << "Rectangle's height is " << p2->getLength() << endl; if (p3 != NULL){ cout << "Triangle's area is " << p3->getArea() << endl; cout << "Triangle's width is " << p3->getHeight() << endl; cout << "Triangle's height is " << p3->getBase() << endl; Joey Paquet, 2007-2014

Polymorphism: virtual methods COMP 345 - Advanced Program Design with C++ Polymorphism: virtual methods Virtual methods allow to declare such a subtype-specific behavior. If an object of type CShape is declared and instantiated with an object of type e.g. CRectangle, calling any of its virtual methods will result in using CRectangle’s behavior, even though its type is declared as CShape. This requires a dynamic run-time binding mechanism. In C++ implementation, it is called “dynamic binding” or “late binding”. class CShape{ protected: double area; string name; public: CShape() : name("anonymous"){ } CShape(string newName) : name(newName){ string getName(){ return name; virtual double getArea()= 0; virtual void print(){ cout << "Shape:" << name << endl; cout << "Area: " << getArea() << endl; }; bool operator < (CShape &s1, CShape &s2){ return (s1.getArea() < s2.getArea()); Joey Paquet, 2007-2014

Polymorphism: virtual methods COMP 345 - Advanced Program Design with C++ Polymorphism: virtual methods Polymorphic behavior comes when you declare an object of a base class type and then instantiate it with an instance of a derived type. In this case, the type of the object can only be determined dynamically at run-time. If a method is declared as virtual, its subtype behavior is branched upon. If a method is not declared as virtual, the base type behavior is branched upon. void main() { CRectangle *shapeRect = new CRectangle("shapeRect", 16.8, 8.8); CCircle *shapeCircle = new CCircle("shapeCircle", 13.8); CTriangle *shapeTriangle = new CTriangle("shapeTriangle", 2.5, 3.8); CShape *shapes[] = { shapeRect, shapeCircle, shapeTriangle }; for (int i = 0; i < sizeof(shapes) / sizeof(shapes[0]); i++){ shapes[i]->getArea(); shapes[i]->print(); if (i>0) cout << "Shape[" << i << "] area (" << shapes[i]->getArea() << ") less than Shape[" << i - 1 << "] area (" << shapes[i-1]->getArea() << ") : " << (*shapes[i] < *shapes[i-1]) << endl; } delete shapeRect; delete shapeCircle; delete shapeTriangle; Joey Paquet, 2007-2014

Virtual methods COMP 345 - Advanced Program Design with C++ class CCircle : public CShape{ double radius; public: CCircle() : CShape(), radius(1){ }; CCircle(string n, double r) : CShape(n), radius(r) { void setRadius(double r) { radius = r; } double getRadius() const { return radius; } double getArea(){ area = 3.14159265 * radius * radius; return area; } void print(){ CShape::print(); cout << "Circle:" << endl; cout << "Radius: " << radius << endl; class CRectangle : public CShape{ double length; double width; public: CRectangle() : CShape(), length(1), width(1){ } CRectangle(string n, double l, double w) : CShape(n), length(l), width(w){ void setLength(double l) { length = l; } void setWidth(double w) { width = w; } double getLength() const { return length; } double getWidth() const { return width; } double getArea(){ area = length * width; return area; void print(){ CShape::print(); cout << "Rectangle:" << endl; cout << "Height: " << length << " Width: " << width << endl; }; Joey Paquet, 2007-2014

Polymorphism: pure virtual methods and abstract classes COMP 345 - Advanced Program Design with C++ Polymorphism: pure virtual methods and abstract classes In C++, some virtual methods can be declared as “pure virtual”. Any class with at least one pure virtual method is an abstract class. No instance of an abstract class can be created. However, an abstract class still represents a data type. To be used, abstract classes need to be derived by subclasses that provide an implementation to all their pure virtual methods. A class that derives an abstract class and does not provide an implementation for all the pure virtual functions it inherits is itself still an abstract class. Contrary to Java interfaces, C++ abstract classes can provide a definition for some of their methods, and can have non-constant data members. Joey Paquet, 2007-2014

Polymorphism: pure virtual methods and abstract classes COMP 345 - Advanced Program Design with C++ Polymorphism: pure virtual methods and abstract classes There are two main uses for pure virtual functions/abstract classes: Classes that are to be used polymorphically with different subclass behaviors. Interfaces, i.e. classes that contain only pure virtual functions. This is equivalent to Java’s interfaces. class CShape{ protected: double area; string name; public: CShape() : name("anonymous"){ } CShape(string newName) : name(newName){ string getName(){ return name; virtual double getArea()= 0; virtual void print(){ cout << "Shape:" << name << endl; cout << "Area: " << getArea() << endl; }; class Iserialisable { public: virtual void load(istream& in) = 0; virtual void save(ostream& out) = 0; virtual ~serialisable(); } Joey Paquet, 2007-2014

COMP 345 - Advanced Program Design with C++ Virtual destructors If you implement a class to be used polymorphically, you probably need to declare its destructor as virtual. If an object of a derived class is assigned to a pointer to a base class, and then later deleted using the base class pointer, the base class destructor will be used to delete the object. The derived class’ destructor will thus never be called, possibly leading to a resource leak. Rule of thumb: always declare the destructor as virtual if a class is to be use polymorphically. class Base { public: virtual ~Base(){ cout << "Base::~Base()" << endl; } }; class Derived : public Base { ~Derived(){ cout << "Derived::~Derived()" << endl; int main(){ Base *b = new Derived(); delete b; int i; cin >> i; Joey Paquet, 2007-2014

COMP 345 - Advanced Program Design with C++ References Mark Radford. C++ Interface Classes - An Introduction. Overload Journal #62 - Aug 2004. Joey Paquet, 2007-2014