← Back to 24T3

Tutorial 8: Polymorphism, Webots II

MTRN2500 24T3



Polymorphism

  1. What is polymorphism?
  1. How does dynamic_cast differ from static_cast ?
  1. Compare the outputs of the below program using Base::print() then a virtually-marked Base::print() . Explain how the virtual keyword creates the discrepancy and enables polymorphism.
#include <iostream> struct Base { void print() { std::cout << "Base\n"; } virtual void print() { std::cout << "Base\n"; } }; struct Derived : public Base { void print() { std::cout << "Derived\n"; } }; int main() { Derived d; Base& b{dynamic_cast<Base&>(d)}; b.print(); }
  1. What compiler error is given here? How can this be fixed (if we do expect the override)?
#include <iostream> class Base { public: void print() { std::cout << "Base\n"; } }; class Derived : public Base { public: void print() override { std::cout << "Derived\n"; } }; int main() { Derived d; d.print(); }
  1. Why does this code throw bad_cast exception when this downcast happens?
#include <iostream> class Base { public: virtual void print() { std::cout << "Base\n"; } }; class Derived : public Base { public: void print() override { std::cout << "Derived\n"; } }; int main() { Base b; Derived& d{dynamic_cast<Derived&>(b)}; }
  1. When defining an abstract class, which methods should be marked as pure virtual? Why are destructors typically pure virtual?

Webots II

The starter code for this tutorial can be found here.

  1. It is possible for Webots controllers to utilise multiple external source and header files. Edit the Makefile in the controller “Files” so that the controller can build without any error. You should not need to edit any other file.
  1. Open the Webots controller “KeyPress”. Implement this controller so that it reads in any key presses via the Keyboard device and writes it directly to the console.

a. Edit the controller so that only “WASD” is printed to the console if these keys are pressed.

  1. Open two Webots controllers “Emitter” and “Receiver” which when assigned to two separate robots will have a one-way communication with each other.

a. Edit “Emitter” so that its Emitter device simply sends some message over and over.

b. Edit “Receiver” so that its Receiver device reads the message from “Emitter” and prints it to console.