Object- Oriented Programming

Iuliana Bocicor

Polymorphism Object-Oriented Programming Static and dynamic binding

Virtual Iuliana Bocicor methods [email protected] Upcasting and downcasting Babes-Bolyai University Abstract classes 2020

1 / 41 Overview

Object- Oriented Programming

Iuliana Bocicor 1 Polymorphism

Polymorphism

Static and 2 Static and dynamic binding dynamic binding

Virtual 3 methods Virtual methods

Upcasting and downcasting 4 Abstract Upcasting and downcasting classes

5 Abstract classes

2 / 41 Primary OOP features

Object- Oriented Programming Abstraction: separating an object’s specification from its Iuliana Bocicor implementation.

Polymorphism

Static and Encapsulation: grouping related data and functions to- dynamic binding gether as objects and defining an interface to those objects.

Virtual methods

Upcasting and Inheritance: allowing code to be reused between related downcasting types. Abstract classes Polymorphism: allowing an object to be one of several types, and determining at runtime how to ”process” it, based on its type.

3 / 41 PolymorphismI

Object- Oriented Programming

Iuliana Definitions Bocicor

Polymorphism Polymorphism is the property of an entity to react differ-

Static and ently depending on its type. dynamic binding Virtual Polymorphism is the property that allows different entities methods

Upcasting and to behave in different ways to the same action. downcasting

Abstract classes Polymorphism allows different objects to respond in differ- ent ways to the same message.

Polymorphism - Greek meaning: ”having multiple forms”.

4 / 41 PolymorphismII

Object- Oriented Programming Usually, polymorphism occurs in situations when one has Iuliana classes related by inheritance. Bocicor

Polymorphism A call to a member function will cause the execution of a Static and dynamic different code, depending on the type of object that invokes binding the function. Virtual methods

Upcasting and downcasting The code to be executed is determined dynamically, at run

Abstract time. classes

The decision is based on the actual object.

5 / 41 PolymorphismIII

Object- Oriented Programming

Iuliana Bocicor

Polymorphism

Static and dynamic binding

Virtual methods

Upcasting and downcasting

Abstract classes

Figure source: https://www.youtube.comwatchv=ng98qapa4Sw

6 / 41 PolymorphismIV

Object- Oriented Programming

Iuliana Bocicor ? In the code below, why are we allowed to write:

Polymorphism Animal* a2 = &p1; ?

Static and dynamic binding Animal a1{"black" , 20}; Virtual Penguin p1{"black and white" , 7 , "Magellanic" } ; methods Animal ∗ a2 = &p1 ; Upcasting and downcasting cout<toString(); //which toString function? Abstract The one from the class Animal, or the one classes from the class Penguin?

7 / 41 Static binding

Object- Oriented Programming

Iuliana Bocicor The choice of which function to call is made at . Polymorphism

Static and dynamic The object a2 is declared as a pointer to Animal ⇒ at binding compile-time it is decided that the function Animal::toString() Virtual methods will be called. Upcasting and downcasting Abstract Static binding is also called early binding. classes

8 / 41 Dynamic bindingI

Object- Oriented Programming In the presented case, the behaviour we expect is a call to Iuliana Bocicor the function Penguin::toString().

Polymorphism Static and At runtime, the actual type of the object is determined. dynamic binding

Virtual methods The decision of using Animal::toString() or Penguin::toString()

Upcasting and should be taken only after determining the actual type of downcasting the object ⇒ at runtime. Abstract classes This is dynamic binding: take the correct decision of which function body to execute, according to the actual type of the object.

9 / 41 Dynamic bindingII

Object- Oriented Programming

Iuliana Dynamic binding is also called late binding. Bocicor

Polymorphism When a message is sent to an object, the code being called Static and dynamic in not determined until runtime. binding

Virtual methods Dynamic binding only works with non-value types: ref- Upcasting and erences and pointers. downcasting

Abstract classes In C++, dynamic binding is achieved using virtual func- tions.

10 / 41 Virtual methodsI

Object- Oriented Programming Iuliana Declaration Bocicor virtual function signature Polymorphism

Static and dynamic binding If a function is declared virtual in a base class and then Virtual overriden in a derived class ⇒ dynamic binding is enabled. methods

Upcasting and downcasting The actual function that is called depends on the content Abstract classes of the pointer (or reference).

The function becomes polymorphic by being designed vir- tual.

11 / 41 Virtual methodsII

Object- Oriented Programming The function in the derived class that is overriding the func- Iuliana tion in the base class can use the override specifier to ensure Bocicor that the function is overriding a virtual function from the Polymorphism base class. Static and dynamic binding override is an identifier with a special meaning when used Virtual methods after member function declarators and otherwise, it is not Upcasting and a reserved keyword. downcasting

Abstract classes DEMO Polymorphic function toString (Animal - Penguin, Dog) (Lec- ture6 demo virtual functions).

12 / 41 C++ mechanismI

Object- Oriented Programming Iuliana In memory, for an object with no virtual functions, only its Bocicor own data is stored. Polymorphism

Static and dynamic Member functions or pointers to them are not stored in the binding object. They are stored in a code memory section, and are Virtual methods known to the compiler. Upcasting and downcasting Abstract When a member function is called, the pointer to the cur- classes rent object (this) is passed as an invisible parameter so the functions know on which object to operate on when they are called.

13 / 41 C++ mechanismII

Object- Oriented Programming Things are different when virtual functions come into play.

Iuliana Bocicor In the case of a derived class with virtual functions, the com- Polymorphism piler creates a table of function addresses called the virtual Static and dynamic table - a static array set up by the compiler at compile time. binding

Virtual methods Every class that uses virtual functions (or is derived from Upcasting and a class that uses virtual functions) will have its own virtual downcasting table. Abstract classes Each entry in the virtual table is a function pointer that points to the most derived function accessible by the class.

14 / 41 C++ mechanismIII

Object- Oriented Programming

Iuliana A pointer to the virtual table (vptr) is added to the base Bocicor class - and inherited by the derived classes. Polymorphism

Static and dynamic When a class object is created, the pointer to the virtual binding table is set to point to the virtual table for that class. Virtual methods

Upcasting and downcasting When a call is made through a pointer or reference, the

Abstract compiler generates code that dereferences the pointer to classes the object‘s virtual table and makes an indirect call using the address of a member function stored in the table.

15 / 41 C++ mechanismIV

Object- Oriented Programming

Iuliana Bocicor

Polymorphism

Static and dynamic binding

Virtual methods

Upcasting and downcasting

Abstract classes

16 / 41 C++ mechanismV

Object- Oriented Programming

Iuliana Bocicor Animal ∗ p = new Penguin { "black and white" , 7 , "Magellanic" } ; Polymorphism

Static and dynamic binding

Virtual methods

Upcasting and downcasting

Abstract classes

17 / 41 C++ mechanismVI

Object- Oriented Programming The virtual function mechanism works only with pointers

Iuliana and references, but not with value-types (objects). Bocicor

Polymorphism Calling a virtual function is slower than calling a non-virtual Static and function: dynamic binding 1 Use the vptr to access the correct virtual table. Virtual 2 Find the correct function to call in the virtual table. methods 3 Call the function. Upcasting and downcasting Abstract Declare functions as virtual only if necessary. classes

DEMO Virtual functions. (Lecture6 demo virtual functions).

18 / 41 Virtual constructors?

Object- Oriented Programming

Iuliana Bocicor Constructors cannot be virtual. Polymorphism

Static and dynamic When creating an object, one must know exactly what type binding of object one is creating. Virtual methods

Upcasting and downcasting Usually, the virtual table pointer is initialized in the con- Abstract structor. classes

19 / 41 Virtual destructorsI

Object- Oriented Programming

Iuliana Bocicor A derived class object contains data from both the base class and

Polymorphism the derived class.

Static and dynamic binding The destructor’s responsibility is to dealocate resources (mem- Virtual ory). methods

Upcasting and downcasting In the case of a derived class object, it is essential that both the Abstract classes destructor of the base class and the destructor of the derived class are called.

20 / 41 Virtual destructorsII

Object- Oriented Programming

Iuliana The correct destructor must be invoked based on the actual type Bocicor of the object, not the type of the pointer holding the reference

Polymorphism to the object.

Static and dynamic binding Therefore, the destructor must have a polymorphic behaviour ⇒ Virtual the base class destructor must be virtual. methods

Upcasting and downcasting

Abstract classes DEMO Virtual destructor. (Lecture6 demo virtual functions).

21 / 41 Upcasting and downcastingI

Object- Oriented Programming Upcasting Iuliana Bocicor Casting an object/reference/pointer of a derived class to an Polymorphism object/reference/pointer of the base class. Static and dynamic binding Casting up the hierarchy. Virtual methods

Upcasting and downcasting Allows us treating a derived type as though it were its base

Abstract type. classes

Is always allowed for public inheritance, without an explicit cast, as a a derived class object has all the members of the base class (and more).

22 / 41 Upcasting and downcastingII

Object- Oriented Programming Downcasting Iuliana Bocicor Casting a base-class pointer/reference to a derived-class Polymorphism pointer/reference. Static and dynamic binding

Virtual Casting down the hierarchy. methods

Upcasting and downcasting Is not allowed without an explicit type cast (requires ex- Abstract classes plicit casting from the user). ? Why?

For explicit casting: static cast, dynamic cast.

23 / 41 Upcasting and downcastingIII

Object- Oriented Programming

Iuliana Bocicor static cast:

Polymorphism converts a reference/pointer to a specified type;

Static and dynamic will check, at compile time, if the types are compatible (in binding the same inheritance hierarchy); Virtual methods

Upcasting and does not perform runtime checking; does not check if the downcasting object being converted is ”complete” ⇒ bad casts can lead Abstract classes to runtime errors.

24 / 41 Upcasting and downcastingIV

Object- Oriented Programming dynamic cast: Iuliana Bocicor converts a reference/pointer to a specified type;

Polymorphism will check, at runtime, if the object can be converted and if Static and dynamic it cannot, it returns nullptr or an error; binding Virtual only works with pointers or references. methods

Upcasting and downcasting Abstract DEMO classes Upcasting and downcasting (Lecture6 demo virtual functions - upCasting() and downCasting()).

25 / 41 Pure virtual functionsI

Object- Oriented Programming

Iuliana Bocicor The definition of a method from a class can be omitted by making the function pure virtual. Polymorphism

Static and dynamic Syntax binding

Virtual virtual function signature =0; methods

Upcasting and downcasting A pure virtual function is a function with no body. Abstract classes All the derived classes will have to define the function.

26 / 41 Pure virtual functionsII

Object- Oriented Programming

Iuliana Bocicor The compiler will reserve a slot for the pure virtual function Polymorphism in the virtual table, but will not add any address in that Static and dynamic particular slot. binding

Virtual methods A destructor can be declared pure virtual, but if any objects Upcasting and downcasting of that class or any derived class are created in the program,

Abstract the destructor shall be defined. classes

27 / 41 Abstract classesI

Object- Oriented Programming A class containing at least one pure virtual function is called Iuliana Bocicor an abstract class.

Polymorphism Static and An abstract class cannot be instantiated (one cannot create dynamic binding objects of that type). Virtual methods Upcasting and There are cases in which one needs the base class only as a downcasting starting point for derived classes. Abstract classes In reality, there are penguins and dogs and koala bears, but no generic animals.

28 / 41 Abstract classesII

Object- Oriented Programming Iuliana When a class is abstract, the compiler will not allow the Bocicor creation of objects of that class. Polymorphism

Static and dynamic An abstract class serves as a base class for a collection of binding related derived classes and it provides: Virtual methods a common public interface (or pure virtual member func- Upcasting and tions); downcasting any shared representation; Abstract classes any shared member functions.

29 / 41 Abstract classesIII

Object- Oriented Programming

Iuliana Extending an abstract class Bocicor

Polymorphism A concrete class that extends an abstract class inherits its

Static and public interface. dynamic binding Virtual A concrete class is expected to have instances. methods

Upcasting and downcasting Override ”abstract” functions to provide specific implemen- Abstract classes tation (otherwise the derived classes will also be abstract classes).

30 / 41 Homogeneous containers and polymorphism

Object- Oriented Programming

Iuliana Bocicor One example of use of polymorphism is on containers hold- ing elements of the ”same type” (from the same class hier- Polymorphism archy). Static and dynamic binding

Virtual A message is sent to each of the objects in the container methods and they must respond in their specific way. Upcasting and downcasting

Abstract classes DEMO Abstract classes. (Lecture6 demo abstract classes).

31 / 41 Pure abstract classesI

Object- Oriented Programming

Iuliana Bocicor A pure abstract class contains nothing but pure virtual methods. Polymorphism

Static and dynamic binding A pure abstract class is also called an interface.

Virtual methods

Upcasting and An interface describes the capabilities of a class without downcasting committing to a particular implementation of that class. Abstract classes The UML representation for abstract entities (functions or classes): italic font.

32 / 41 Pure abstract classesII

Object- Oriented Programming

Iuliana Bocicor Remember Lab5 - 10 from Fundamentals of Programming? Polymorphism

Static and dynamic We started with an in-memory repository, and added a file- binding based one. Virtual methods

Upcasting and downcasting Defining an interface would allow us to use any class that

Abstract implements it. classes

33 / 41 Pure abstract classesIII

Object- Oriented Programming

Iuliana Bocicor

Polymorphism

Static and dynamic binding

Virtual methods

Upcasting and downcasting

Abstract classes

34 / 41 Example - pure abstract classI

Object- Oriented Programming Requirement: given a list of animals, display, in turns, the Iuliana Bocicor animals having: the weight smaller than a given value; Polymorphism the colour equal to a given colour. Static and dynamic binding

Virtual methods

Upcasting and downcasting

Abstract classes

35 / 41 Example - pure abstract classII

Object- Oriented Programming

Iuliana Bocicor

Polymorphism Static and DEMO dynamic binding Abstract classes. (Lecture6 demo abstract classes - Filter.h and Virtual methods filterAnimals()).

Upcasting and downcasting

Abstract classes

36 / 41 ExerciseI

Object- Oriented Programming

Iuliana Bocicor

Polymorphism

Static and dynamic binding Write the C++ code corresponding to the following UML class

Virtual diagram related to companies and their employees. methods

Upcasting and downcasting

Abstract classes

37 / 41 ExerciseII

Object- Oriented Programming

Iuliana Bocicor

Polymorphism

Static and dynamic binding

Virtual methods

Upcasting and downcasting

Abstract classes

38 / 41 ExerciseIII

Object- Oriented Programming

Iuliana The company has several employees, some of them are man- Bocicor agers. Polymorphism The toString method from Employee returns a string with Static and dynamic the name of the employee. binding The toString method from Manager returns a string with Virtual methods the word ”Manager” and the name of the employee. Upcasting and downcasting The computeSalary method from Employee returns the Abstract base salary. classes The computeSalary method from Manager returns the base salary, to which the manager bonus is added.

39 / 41 ExerciseIV

Object- Oriented Programming

Iuliana Bocicor Write a test program that creates several employees (both

Polymorphism regular employees and managers), add all the employes into Static and a list (vector). dynamic binding

Virtual methods Create a function that for a list of employees will print out

Upcasting and the proper name and salaries for all the employes, using downcasting the values returned by the toString and computeSalary Abstract classes methods.

40 / 41 Inheritance and polymorphism - benefits

Object- Oriented Programming

Iuliana Bocicor code reuse:

Polymorphism derived classes inherit from the base class;

Static and code duplication is avoided ⇒ better maintanance, evolu- dynamic tion, understanding. binding

Virtual methods extensibility: Upcasting and downcasting generic code;

Abstract new functionalities can be added without modifying the ex- classes isting code; extension points are provided for further evolution.

41 / 41