0
0
C++programming~10 mins

Method overriding 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'
Aoutput
Bdisplay
Cprint
Dshow
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using a different method name than the one overridden in the derived class.
2fill in blank
medium

Complete the code to override the base class method 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'
Adisplay
Bprint
Cshow
Doutput
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using a different method name, which does not override the base method.
3fill in blank
hard

Fix the error in the code by completing the method declaration to enable overriding.

C++
class Base {
public:
    [1] void display() {
        std::cout << "Base function" << std::endl;
    }
};
Drag options to blanks, or click blank then click option'
Adisplay
Bvirtual void display
Coverride display
Dvirtual
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Omitting the virtual keyword, which disables overriding.
4fill in blank
hard

Fill both blanks to correctly override the base class method and call it from the derived class.

C++
class Derived : public Base {
public:
    void [1]() override {
        Base::[2]();
        std::cout << "Derived override" << std::endl;
    }
};
Drag options to blanks, or click blank then click option'
Adisplay
Bshow
Dprint
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using different method names that do not match the base class.
5fill in blank
hard

Fill all three blanks to create a base class with a virtual method, override it in the derived class, and call the method via a base pointer.

C++
class Base {
public:
    [1] void display() {
        std::cout << "Base display" << std::endl;
    }
};

class Derived : public Base {
public:
    void [2]() override {
        std::cout << "Derived display" << std::endl;
    }
};

int main() {
    Base* ptr = new Derived();
    ptr->[3]();
    delete ptr;
    return 0;
}
Drag options to blanks, or click blank then click option'
Avirtual
Bdisplay
Doverride
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Not marking the base method as virtual, so overriding does not work.
Forgetting the override keyword in the derived class.
Calling a wrong method name via pointer.