Polymorphism with Virtual Functions in C++: Global print Function Example, Lecture notes of Physics

The concept of polymorphism in C++ using virtual functions and provides examples of global print functions by reference and pointer. It discusses static or early binding and dynamic or late binding, and the differences between them. The document also covers the concept of virtual functions, their declaration, and the benefits and drawbacks of using them.

Typology: Lecture notes

2021/2022

Uploaded on 09/27/2022

riciard
riciard 🇬🇧

4.4

(7)

233 documents

1 / 16

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Comp151
Polymorphism: Virtual Functions
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Polymorphism with Virtual Functions in C++: Global print Function Example and more Lecture notes Physics in PDF only on Docsity!

Comp

Polymorphism: Virtual Functions

Example: Global print Function By Reference

Because of the substitution principle, you may want to write aglobal print function for Person and its derived classes asfollows:

void print_by_ref(const Person& person) { person.print(); } int main() { Person mouse(''Mickey'', ''Disney World'', arts); Teacher einstein(''Albert Einstein'', ''USA'', physics, professor); Student plato(''Plato'', ''Greece'', philosophy); plato.enroll_course(COMP151); print_by_ref(mouse); print_by_ref(einstein); print_by_ref(plato); }

Example: Output

------ Person details ------ Name: Mickey Addr: Disney World Dept: 0 ------ Person details ------ Name: Albert Einstein Addr: USA Dept: 1 ------ Person details ------ Name: Plato Addr: Greece Dept: 2 Oops!

Example: This Is What We Want

(assume: enum Department { arts, physics, philosophy, ..

----- Person details ----- Name: Mickey Addr: Disney World Dept: 0 ----- Teacher details ----- Name: Albert Einstein Addr: USA Dept: 1 Rank: Full Professor ----- Student details ----- Name: Plato Addr: Greece Dept: 2 Enrolled in: COMP

Dynamic or Late Binding

By default, C++ uses static binding. (Same as C, Pascal,and FORTRAN.)

In C++, another type of binding called dynamic binding issupported through virtual functions. (Same as Java,Smalltalk, Lisp/Scheme.)

When dynamic binding is used, the method to be called isselected using the actual type of the object in the call, i.e.,print_by_ref(mouse)

(a Person object) would call

Person::print()

print_by_ref(plato)

(a Student object) would call

Student::print()

and

print_by_ref(einstein)

(a Teacher object) would call

Teacher::print().

Note that the possible object types do not need to be known atthe time that the function call is being compiled!

Virtual Functions

A virtual function is a method that is declared using the virtualkeyword in the class definition (but not in the methodimplementation, if it is outside the class).

class Person { string name; string address; Department dept; public: virtual void print() const; … }; void Person::print() const { cout << '‘--- Person details ---'' << endl; cout << ''Name: '' << name << endl; cout << ''Addr: '' << address << endl; cout << ''Dept: '' << dept << endl; }

Polymorphism

Polymorphism in C++ means that we can work with objectswithout knowing their precise type at compile time:

In:

void print_by_ptr(const Person* person) { person->print(); }

the type

of the object pointed to by person is not known to theprogrammer writing this code, nor to the compiler. We say thatperson exhibits polymorphism, because the object can take onmultiple shapes.

Polymorphism allows us to write programs that behave correctlyeven when used with objects of derived classes.

A pointer or reference must be used to have polymorphism. Ifcall-by-value is used, no polymorphism can happen (WHY?).

void print_by_value(Person person) { person.print(); } /* wrong use */

poly

= multiple

morphos

= shape

Example: Virtual Function

#include ''people.hpp'' // class Person { ... virtual void print() const; } // class Teacher: public Person { ... virtual void print() const; } // class Student: public Person { ... virtual void print() const; } // class PG Student: public Student { ... virtual void print() const; } void print_by_ref(const Person& person) { person.print(); } void print_by_ptr(const Person* person) { person->print(); } int main() { const int N = 4; Person p(' 'Mickey'', ''Disney World'', arts); Teacher t(''Albert Einstein'', ''USA'', physics, professor); Student s(''Plato'', ''Greece'', philosophy); s.enroll_course(''COMP151''); PG Student g('‘John'', ''HK'', computer sci, ''AI''); g.enroll_course(''COMP527''); Person* x[N]; x[0] = &p; x[1] = &t; x[2] = &s; x[3] = &}; for (int j = 0; j < N; ++j) // by pointer to the base class x[j]->print(); cout << endl; for (int j = 0; j < N; ++j) // by pointer to the base class print_by_ptr(x[j]); cout << endl; for (int j = 0; j < N; ++j) // by reference to the base class print_by_ref(*(x[j])); }

main() { Base base; X x; Y y; Base* A[3]; A[0] = &base; A[1] = &x; A[2]= &y; for (int j = 0; j<3; j++) // Pointers A[j]->Display(); cout << endl; for (int j = 0; j<3; j++) // Passing references Display_by_ref(*(A[j])); cout << endl; for (int j = 0; j<3; j++) // Passing pointers Display_by_pntr(A[j]); } OUTPUT ------ Inside Base::Display Inside Base::Display Inside Base::Display Inside Base::Display Inside Base::Display Inside Base::Display Inside Base::Display Inside Base::Display Inside Base::Display

Another Example: Virtual Function

// Virtual.cpp # include using namespace std; class Base {

public: virtual void Display() const; } ; class X: public Base { public: virtual void Display() const; }; class Y: public Base { public: virtual void Display() const; }; void Base::Display() const { cout << ''Inside Base::Display\n''; } void X::Display() const { cout << ''Inside X::Display\n''; } void Y::Display() const { cout << ''Inside Y::Display\n''; } void Display_by_val(Base b) { b.Display(); } void Display_by_ref(const Base& b) { b.Display(); } void Display_by_pntr(Base* b) { b->Display(); }

Output ------ Inside Base::Display Inside X::Display Inside Y::Display Inside Base::Display Inside Base::Display Inside Base::Display Inside Base::Display Inside X::Display Inside Y::Display Inside Base::Display Inside X::Display Inside Y::Display