0
0
C++programming~10 mins

Virtual functions 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 named display in the base class.

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

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

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

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

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

Fill both blanks to declare a pure virtual function show in the base class and override it in the derived class.

C++
class Base {
public:
    virtual void [1]() [2];
};
Drag options to blanks, or click blank then click option'
Ashow
Bdisplay
C= 0
D{}
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Not using '= 0' to make the function pure virtual.
Using the wrong function name.
5fill in blank
hard

Fill all three blanks to implement the derived class overriding the pure virtual function show and calling it.

C++
class Derived : public Base {
public:
    void [1]() override [2];
};

int main() {
    Base* obj = new Derived();
    obj->[3]();
    delete obj;
    return 0;
}
Drag options to blanks, or click blank then click option'
Adisplay
Bshow
C()
D{}
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using wrong function names.
Missing function body braces.
Incorrect function call syntax.