0
0
C++programming~10 mins

Runtime polymorphism in C++ - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a virtual function in the base class.

C++
class Base {
public:
    virtual void [1]() {
        std::cout << "Base function" << std::endl;
    }
};
Drag options to blanks, or click blank then click option'
Adisplay
Bshow
Cprint
Doutput
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using a function name not matching the derived class function.
Forgetting to mark the function as virtual.
2fill in blank
medium

Complete the code to override the virtual function in the derived class.

C++
class Derived : public Base {
public:
    void [1]() override {
        std::cout << "Derived function" << std::endl;
    }
};
Drag options to blanks, or click blank then click option'
Aprint
Bshow
Cdisplay
Doutput
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using a different function name than the base class.
Omitting the override keyword.
3fill in blank
hard

Fix the error in the code to call the derived class function through a base class pointer.

C++
Base* ptr = new Derived();
ptr->[1]();
Drag options to blanks, or click blank then click option'
Ashow
Bdisplay
Cprint
Doutput
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Calling a function name not declared in the base class.
Not using a pointer or reference to base class.
4fill in blank
hard

Fill both blanks to define a base class pointer and call the virtual function.

C++
Base* [1] = new [2]();
[1]->display();
Drag options to blanks, or click blank then click option'
Aptr
BDerived
CBase
Dobj
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using different names for pointer variable.
Creating an object of base class instead of derived.
5fill in blank
hard

Fill all three blanks to create a vector of base class pointers and call the virtual function on each.

C++
#include <vector>
#include <iostream>

std::vector<Base*> [1];
[1].push_back(new [2]());
[1].push_back(new [3]());

for (auto ptr : [1]) {
    ptr->display();
}
Drag options to blanks, or click blank then click option'
Aobjects
BDerived
CBase
Ditems
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using different vector names in different places.
Adding base class objects instead of derived class objects.