Virtual Functions Junaed Sattar November 10, 2008 Lecture 10.

Slides:



Advertisements
Similar presentations
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Advertisements

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.
Object-Oriented Programming in C++ Lecture 7 Polymorphism.
. Virtual Classes & Polymorphism. Example (revisited) u We want to implement a graphics system u We plan to have lists of shape. Each shape should be.
Polymorphism From now on we will use g++!. Example (revisited) Goal: Graphics package Handle drawing of different shapes Maintain list of shapes.
12/08/08MET CS Fall Polymorphism 10. Polymorphism Goal: Goal: Create methods that can be invoked with all object types, base as well as.
PolymorphismCS-2303, C-Term Polymorphism Hugh C. Lauer Adjunct Professor (Slides include materials from The C Programming Language, 2 nd edition,
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
Chapter 4 Inheritance Bernard Chen Spring Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
1 Data Structures - CSCI 102 CS102 C++ Polymorphism Prof Tejada.
Pointer Data Type and Pointer Variables
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
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.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Chapter 15 – Inheritance, Virtual Functions, and Polymorphism
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
Polymorphism &Virtual Functions
Polymorphism &Virtual Functions 1. Polymorphism in C++ 2 types ▫Compile time polymorphism  Uses static or early binding  Example: Function and operator.
Object-Oriented Programming: Polymorphism 1. OBJECTIVES What polymorphism is, how it makes programming more convenient, and how it makes systems more.
Chapter 15 Polymorphism and Virtual Functions. Learning Objectives Virtual Function Basics – Late binding – Implementing virtual functions – When to use.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Unit IV Unit IV: Virtual functions concepts, Abstracts classes & pure virtual functions. Virtual base classes, Friend functions, Static functions, Assignment.
OOP and Dynamic Method Binding Chapter 9. Object Oriented Programming Skipping most of this chapter Focus on 9.4, Dynamic method binding – Polymorphism.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Chapter 10 Inheritance and Polymorphism
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
C/C++ 3 Yeting Ge. Static variables Static variables is stored in the static storage. Static variable will be initialized once. 29.cpp 21.cpp.
CSCI-383 Object-Oriented Programming & Design Lecture 18.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Chapter -6 Polymorphism
Inheritance Initialization & Destruction of Derived Objects Protected Members Non-public Inheritance Virtual Function Implementation Virtual Destructors.
Overview of C++ Polymorphism
Variations on Inheritance Object-Oriented Programming Spring
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.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
CSC241 Object-Oriented Programming (OOP) Lecture No. 17.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
A First Book of C++ Chapter 12 Extending Your Classes.
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.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
7. Inheritance and Polymorphism
Class A { public : Int x; A()
Polymorphism.
Inheritance & Polymorphism
Polymorphism & Virtual Functions
Polymorphism Lec
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Virtual Functions Department of CSE, BUET Chapter 10.
Polymorphism Polymorphism
Inheritance: Polymorphism and Virtual Functions
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
Polymorphism Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan.
CISC/CMPE320 - Prof. McLeod
Inheritance: Polymorphism and Virtual Functions
CISC/CMPE320 - Prof. McLeod
Overview of C++ Polymorphism
Inheritance: Polymorphism and Virtual Functions
CS410 – Software Engineering Lecture #8: Advanced C++ III
Static Binding Static binding chooses the function in the class of the base class pointer, ignoring any versions in the class of the object actually.
Computer Science II for Majors
Presentation transcript:

Virtual Functions Junaed Sattar November 10, 2008 Lecture 10

Today Inheritance types Virtual functions  how  why  run-time (a.k.a “true”) polymorphism

Access specifiers classes can be inherited public, protected, or private  we've seen public inheritance The difference?

Inheritance Summary

Constructor/Destructor Order Destructors, constructors, and assignment operators are not inherited  they may be called automatically were necessary Constructors are called from the “bottom up” Destructors are called from the “top down”

Example class Base { public: Base() { cout << "calling base constructor." << endl; } ~Base() { cout << "calling base destructor." << endl; } }; class Derived1: public Base{ public: Derived1() { cout << "calling derived1 constructor." << endl; } ~Derived1() { cout << "calling derived1 destructor." << endl; } }; class Derived2 :public Derived1{ public:Derived2() { cout << "calling derived2 constructor." << endl; } ~Derived2() { cout << "calling derived2 destructor." << endl; } }; int main(){ Derived2 d; }

Output calling base constructor. calling derived1 constructor. calling derived2 constructor. calling derived2 destructor. calling derived1 destructor. calling base destructor.

Virtual Functions C++ matches a function call with the correct function definition at compile time  known as static binding the compiler can match a function call with the correct function definition at run time  known as dynamic binding.  declare a function with the keyword virtual if you want the compiler to use dynamic binding for that specific function.

Virtual Functions The virtual keyword indicates to the compiler that  it should choose the appropriate definition of a function not by the type of reference, but by the type of object that the reference refers to.

Virtual Methods Therefore,  a virtual function is a member function you may redefine for other derived classes,  can ensure that the compiler will call the redefined virtual function for an object of the corresponding derived class,  even if you call that function with a pointer or reference to a base class of the object. A class that declares or inherits a virtual function is called a polymorphic class.

Declaring virtual prefix declaration with the virtual keyword redefine a virtual member function in any derived class this is called overriding  understand the contrast with overloading

More on definition overridden function must have same name and same parameter list  no need to use the virtual keyword again  return type can be different if the parameter lists are different, they are considered different  in this case, it is not overridden, but hidden  hidden methods cannot be called

Example class A { public: virtual void f() { cout << "Class A" << endl; } }; class B: public A { public: void f(int) { cout << "Class B" << endl; } }; class C: public B { public: void f() { cout << "Class C" << endl; } };

Output int main() { B b; C c; A* pa1 = &b; A* pa2 = &c; // b.f(); pa1->f(); pa2->f(); } Outputs: Class A Class C

Synopsis b::f() is not allowed  it hides A::f() (a virtual function)‏  not overloading (why?)‏ method overloading must happen within the same class, not in inheritance hierarchies c::f() is allowed  virtual, overrides A::f()‏

So, why? a hierarchy of geometric shape classes  draws circles, ellipses, rectangles etc just use method draw throughout the hierarchy Line RectangleCircle SquareEllipse draw()‏

More why to enforce a software design  developers must define their own implementation e.g. ImagingDevice objects (webcam, firewire, disk images, movies..)‏  must acquire frames in their own way  should have uniform interface (hiding implementation details)‏ use pure virtual methods

“Pure”ly Virtual a virtual function declared with no definition  base class contains no implementation at all class containing a pure virtual function is an abstract class  similar to Java interfaces  cannot instantiate from abstract classes enforces a design through inheritance hierarchy  inherited classes must define implementation

Example class A { public: virtual void f() = 0; // pure virtual }; class B: public A { public: void f() { cout << "Class B" << endl; } }; class C: public B { public: void f() { cout << "Class C" << endl; } };

Output int main() { B b; C c; A* pa1 = &b; A* pa2 = &c; pa1->f(); pa2->f(); } Outputs: Class B Class C

Another example class ImagingDevice { protected: unsigned char *buffer; int width, height;... public: ImagingDevice(); virtual ~ImagingDevice(); // virtual destructor... virtual bool InitializeDevice() = 0; virtual bool GetImage()=0; virtual bool UninitializeDevice() = 0; virtual void SaveImage()=0;... };

Continuing class USBDevice: public ImagingDevice {... public: USBDevice(); virtual ~USBDevice();... }; bool USBDevice::InitializeDevice(){... } bool USBDevice::UninitializeDevice(){... } bool USBDevice::GetImage(){... } void USBDevice::SaveImage(){... }

Why virtual destructor? for properly cleaning up dynamically allocated memory class Base{ public: Base(){}... }; class Derived: public Base { int *memory; public: Derived(){ memory = new int[1000]; } ~Derived(){ delete [] memory; } }

Virtual Destructor int foo() { Base *b = new Derived();... delete b; // will not call destructor of d, as it // should, (why?)‏ }

Diagnosis If not declared virtual, compiler uses type of pointer to decide which method to call  in this case, b is of type Base, so the Base destructor will get called  memory leak from d (how?)‏ solution: always declare destructors virtual, even if no other virtual functions

Next Generic programming with templates The Standard Template Library