Virtual Functions, Pure Functions & Abstract Base Classes, Exercises of Advanced Computer Programming

The derived class can provide its own version of a function that appears in the base class. (Note that a function is determined by its name.

Typology: Exercises

2022/2023

Uploaded on 02/28/2023

gabryel
gabryel 🇺🇸

4.6

(18)

255 documents

1 / 8

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Virtual Functions, Pure Functions &
Abstract Base Classes
pf3
pf4
pf5
pf8

Partial preview of the text

Download Virtual Functions, Pure Functions & Abstract Base Classes and more Exercises Advanced Computer Programming in PDF only on Docsity!

Virtual Functions, Pure Functions &

Abstract Base Classes

Casting

We saw the following:

Base *R = new Derived(); // okay

To use the member functions of Derived, one has to “remind” the compiler that we know that the object R is pointing to is a Derived object:

Derived Q = static_cast<Derived> (R);

Virtual and Nonvirtual

If a function is labeled virtual in the Base class, then the Derived version of a function is always used.

Otherwise, which version is used is determined by how the object is referenced. (We omit the details.)

Comment on Virtual Functions

Note that if a function is labeled virtual in the Base class, it is automatically virtual in the Derived class.

In Java all functions are implicitly virtual

Pure Functions

A virtual function might have no implementation at all in the Base class. This is indicated by writ- ing

virtual void scream( ) = 0;

in the class definition.

Abstract Base Classes

An abstract base class is one with at least one pure function. We cannot instantiate an object of an abstract base class.

(Java: An interface is a class without mem- ber variables all of whose member functions are pure.)