welcome to introduction to object-oriented programming (oop) · object slicing actually removes...

Post on 20-Jul-2020

9 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

QUIZ

Write the following for the class Bar:

• Default constructor

• Constructor

• Copy-constructor

• Overloaded assignment oper.

• Is a destructor needed?

Or Foo(x), depending on how we want the initialization

to be made.

Criticize!

Ch. 15: Polymorphism &Virtual Functions

Virtual functions enhance the concept of type.

There is no analog to the virtual function in a traditional procedural language. As a procedural programmer, you have no referent with which to think about virtual functions, as you do with almost every other feature in the language.

Features in a procedural language can be understood on an algorithmic level, but, in an OOL, virtual functions can be understood only from a design viewpoint.

text

Remember upcasting

Draw the UML diagram!

We would like the more specific version of play() to be called, since flute is a Wind object, not a generic Instrument.

Ch. 1: Introduction to Objects

Remember from ch.1 …

Early binding vs. late binding

“The C++ compiler inserts a special bit of code in lieu of the absolute call. This code calculates the address of the function body, using information stored in the object at runtime!”

text

Ch. 15: Polymorphism &Virtual Functions

virtual functions

To cause late binding to occur for a particular function, C++ requires that you use the virtualkeyword when declaring the function in the base class.

All derived-class functions that match the signature of the base-class declaration will be called using the virtual mechanism.

text

example

It is legal to also use the virtual keyword in the derived-class

declarations, but it is redundant and can

be confusing.

Extensibility“With play( ) defined as virtual in the base class, you can add as many new types as you want without changing the tune( ) function.

In a well-designed OOP program, most or all of your functions will follow the model of tune( ) and communicate only with the base-class interface. Such a program is extensible because […] the functions that manipulate the base-class interface will not need to be changed at all to accommodate the new classes.”

text

Read and understand the full program C15:Instrument4.cpp

How C++ implements late binding

The typical compiler creates a single table (called the VTABLE) for each class that contains virtual functions. The compiler places the addresses of the virtual functions for that particular class in the VTABLE.

In each class with virtual functions, it secretly places a pointer, called the vpointer (abbreviated as VPTR), which points to the VTABLE for that object.

text

If function is not overridden in the base class, the address of its base-class version is placed in the VTABLE.

Here’s what a call to adjust( ) for a Brass object looks like, if made through an Instrument pointer:

(An Instrument reference produces the same result)

The memory overhead is only one pointer, no matter how many virtual functions there are!

Installing the vpointer

This is where the default constructor is essential:

In the Instrument examples, the compiler creates a default constructor that does nothing except initialize VPTR.

This constructor, of course, is automatically called for all Instrument objects before you can do anything with them, so you know that it’s always safe to call virtual functions.

Objects are different

“[…] upcasting deals only with addresses ” (?)

Means: Upcasting is not necessarily implemented by the compiler via late binding.

• Actually, if given the choice, the compiler will probably prefer early binding, since it results in faster code.

But when the compiler does not “have” the object (i.e. when the object is passed by pointer or reference), it must use late binding.

early binding ? and references ?

Code example

Abstract base classes and pure virtual functions

Often in a design, you want the base class to present only an interface for its derived classes. That is, you don’t want anyone to actually create an object of the base class, only to upcast to it so that its interface can be used.

We say that the virtual function is pure.

These functions exist only to create a common interface for all the derived classes.

A class with only pure virtual functions is called a pure abstract class.

Code example

The compiler still reserves a slot for a pure virtual function in the VTABLE, but does not to put an address in that particular slot.

QUIZ

Write a pure virtual function foo in the parent class, and redefine it as a virtual function in the child class.

QUIZ

In practical terms, what is the difference between a virtual function and a pure virtual one?

Solution

In practical terms, what is the difference between a virtual function and a pure virtual one?

A: If a class has a pure virtual function, no objects of that class can be instantiated.

QUIZ

Does this code compile?

(Assume that Abstract::bar and Derived::foo are defined in another file.)

Source: http://stackoverflow.com/questions/8931612/do-all-virtual-functions-need-to-be-implemented-in-derived-classes

int main(){

Derived d;

}

Solution

Yes. A derived class does not need to override virtual functions from the parent, only purevirtual ones!

int main(){

Derived d;

}

Actually, not every derived class needs to override the pure virtuals from the parent!

A function can stay pure virtual in several levels of the hierarchy.

(But, eventually, allpure virtuals must be overriden in order to be able to instantiate objects.)

int main(){

DerivedMore dm;

}

Virtual functions in multi-level hierarchies

Individual work for next time:

• Read and understand the section–Under the hood

–Why virtual functions?

• End-of-chapter exercise 1

EOL 1

QUIZHow is the late binding of virtual

functions implemented in the C++ compiler?

How C++ implements late binding

The typical compiler creates a single table (called the VTABLE) for each class that contains virtual functions. The compiler places the addresses of the virtual functions for that particular class in the VTABLE.

In each class with virtual functions, it secretly places a pointer, called the vpointer (abbreviated as VPTR), which points to the VTABLE for that object.

text

QUIZWhy do we need virtual functions?

virtual functions

To cause late binding and upcasting to occur for a particular function, C++ requires that you use the virtual keyword when declaring the function in the base class.

All derived-class functions that match the signature of the base-class declaration will be called using the virtual mechanism.

text

QUIZWhy do we need pure virtual

functions?

Abstract base classes and pure virtual functions

Often in a design, you want the base class to present only an interface for its derived classes. That is, you don’t want anyone to actually create an object of the base class, only to upcast to it so that its interface can be used.

We say that the virtual function is pure.

Common misconception:

It’s illegal to provide a definition for a

pure virtual function

But, wait a second: If we cannot instantiate objects of type Abstract, what use can the definition be?

It is legal to provide a

definition for a pure virtual

function!

We can always access the parent function using the scope resolution operator!

… however, the pure virtual function definition cannot be inline:

QUIZ: Show how to access the Pet pure virtual code in main

Inheritance and the VTABLE

It is also possible to add new virtual functions to the derived class.

example

VTABLEs created by the compiler for Pet and Dog:

VTABLEs created by the compiler for Pet and Dog:

Problem: We cannot use sit() with an upcast pointer or reference!

This is the opposite of upcasting – It is called downcasting.

Solution: typecast manually!

Extra-credit quiz

Ch. 3: The C in C++

C++ explicit casts

Back to Ch.15

RTTI is all about casting base-class pointers down to derived-class pointers (“up” and “down” are relative to a typical class diagram, with the base class at the top). • Casting up happens automatically, with no coercion, because it’s

completely safe. • Casting down is unsafe because there’s no compile time

information about the actual types, so you must know exactly what type the object is. If you cast it into the wrong type, you’ll be in trouble.

Run-time type identification (RTTI)

dynamic_cast does its work at runtime, using the virtual table• It tends to be more expensive than the other C++-style

casts.

Run-time type identification (RTTI)

QUIZ

Is this use of the function sit( ) correct? Explain.

Solution

Is this use of the function sit() correct? Explain.

Yes. Remember that, when the compiler “has” the actual object, it uses early binding, so the VTABLE never comes into play.

Polymorphism - definition

It is the virtual function mechanism described in this chapter, involving the VTABLE, VPTRs, upcasting, downcasting and RTTI.

It allows late binding to occur.

Object slicingor

Why we should not use pass-by-value with polymorphism

Do you remember how parameters are passed to a function?

An object the size of Pet is pushed on the stack (and cleaned up after the call)

Fluffy is sliced

Do. Not. Slice. Fluffy.

Object slicing actually removes part of the object as it copies it into the new object (rather than simply changing the meaning

of an address, as when using a pointer or reference).

Because of this, upcasting into an object is not done often; in fact, it’s usually something to watch out for and prevent.

Overloading & overriding

In Chapter 14, we learned that redefining an overloaded function in the base class hides all of the other base-class versions of that function.

When virtual functions are involved the behavior is a little different.

The base class is expecting an int to be returned from f( ). The derived-class version of f( ) must keep that contract!

Does this mean that we cannot modify the return type of a virtual function during overriding?

Does this mean that we cannot modify the return type of a virtual function during overriding?

In general, yes!

… but there is a special case in which we can slightly modify the return type:If returning a pointer or a reference to a base class, the overridden version of the function may return a pointer or reference to a class derived from that base.This is called …

Variant return type

Note: Returning the base type will generally solve your problems so this is a rather specialized feature.

This is another application of dynamic_cast!

Draw the UML class diagram!

Same as in base class, no

new rule need aply.

The variant type rule allows this:

The return type is more derived than in the base

class (but inherited from it!!)

No problem, the two types agree.

Need a downcast (less safe!)

Example user code

We stop before the section

virtual functions & constructors

and we skip the remainder of this chapter.

Individual work / review for Ch.15:

End-of-chapter exercises 2, 3

EOL 2

top related