0
0
C++programming~10 mins

Why inheritance is used in C++ - Test Your Understanding

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

Complete the code to declare a class Dog that inherits from Animal.

C++
class Dog : public [1] {
};
Drag options to blanks, or click blank then click option'
AAnimal
BDog
CCat
DVehicle
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using the same class name for inheritance (Dog inherits Dog).
Using unrelated class names like Vehicle.
2fill in blank
medium

Complete the code to call the base class constructor from the derived class Car.

C++
class Vehicle {
public:
    Vehicle(int wheels) {}
};

class Car : public Vehicle {
public:
    Car() : [1](4) {}
};
Drag options to blanks, or click blank then click option'
ACar
Bint
Cwheels
DVehicle
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Calling the derived class constructor inside itself.
Using variable names instead of class names.
3fill in blank
hard

Fix the error in the code to correctly override the makeSound method in the derived class Cat.

C++
class Animal {
public:
    virtual void makeSound() {
        std::cout << "Some sound" << std::endl;
    }
};

class Cat : public Animal {
public:
    [1] void makeSound() override {
        std::cout << "Meow" << std::endl;
    }
};
Drag options to blanks, or click blank then click option'
Aoverride
Bvirtual
Cvoid
Dpublic
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Omitting the return type.
Using 'override' keyword without proper syntax.
4fill in blank
hard

Fill both blanks to create a derived class Bird that inherits publicly from Animal and overrides the fly method.

C++
class Animal {
public:
    virtual void fly() {
        std::cout << "Cannot fly" << std::endl;
    }
};

class Bird : [1] [2] {
public:
    void fly() override {
        std::cout << "Flying high" << std::endl;
    }
};
Drag options to blanks, or click blank then click option'
Apublic
Bprivate
CAnimal
DBird
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using private inheritance which hides base class methods.
Using the derived class name instead of the base class name.
5fill in blank
hard

Fill all three blanks to create a dictionary-like map of animal names to their sound lengths, filtering only those with sound length greater than 3.

C++
std::map<std::string, int> soundLengths = {
    {"dog", 3},
    {"elephant", 8},
    {"cat", 3},
    {"bird", 4}
};

std::map<std::string, int> filtered;
for (const auto& [1] : soundLengths) {
    if ([2].second [3] 3) {
        filtered.insert([2]);
    }
}
Drag options to blanks, or click blank then click option'
Aentry
C>
D<
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using different variable names inconsistently.
Using < instead of > causing wrong filtering.