0
0
C++programming~10 mins

Abstract classes 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 an abstract class with a pure virtual function.

C++
class Shape {
public:
    virtual void draw() [1];
};
Drag options to blanks, or click blank then click option'
A()
B{}
C;
D= 0
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Forgetting to add = 0 makes the function not pure virtual.
Using empty braces {} defines a normal function, not pure virtual.
2fill in blank
medium

Complete the code to prevent instantiation of the abstract class.

C++
Shape s; // Error: cannot instantiate abstract class

class Shape {
public:
    virtual void draw() = [1];
};
Drag options to blanks, or click blank then click option'
A0
B1
Cnull
Dvoid
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using = 1 or other values instead of = 0.
Trying to instantiate an abstract class causes a compile error.
3fill in blank
hard

Fix the error in the derived class by correctly overriding the pure virtual function.

C++
class Circle : public Shape {
public:
    void draw() [1] {
        // draw circle
    }
};
Drag options to blanks, or click blank then click option'
A()
B() override
C(int) override
D(void) override
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Changing the parameter list causes the function not to override.
Omitting override keyword is allowed but not recommended.
4fill in blank
hard

Fill both blanks to declare an abstract class with a pure virtual destructor and a pure virtual function.

C++
class Interface {
public:
    virtual ~Interface() [1];
    virtual void execute() [2];
};
Drag options to blanks, or click blank then click option'
A= 0
B{}
C;
D()
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Forgetting to define a virtual destructor causes undefined behavior.
Using empty braces {} instead of = 0 does not make the function pure virtual.
5fill in blank
hard

Fill all three blanks to implement a derived class that overrides all pure virtual functions and destructor.

C++
class Derived : public Interface {
public:
    ~Derived() [1] override {}
    void execute() [2] override {
        // implementation
    }
    void extra() [3] {
        // extra method
    }
};
Drag options to blanks, or click blank then click option'
A()
D(int)
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Changing parameter lists breaks overriding.
Forgetting override keyword can cause silent errors.