0
0
C++programming~10 mins

Base and derived 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 a base class named Animal.

C++
class [1] {
public:
    void speak() {
        std::cout << "Animal sound" << std::endl;
    }
};
Drag options to blanks, or click blank then click option'
ADog
BAnimal
CCat
DBird
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using a derived class name instead of the base class name.
Misspelling the class name.
2fill in blank
medium

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

C++
class Dog : public [1] {
public:
    void speak() {
        std::cout << "Woof!" << std::endl;
    }
};
Drag options to blanks, or click blank then click option'
AAnimal
BCat
CBird
DFish
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using a class name that is not the base class.
Forgetting the public keyword.
3fill in blank
hard

Fix the error in the code to call the base class speak() method inside the derived class Dog's speak() method.

C++
class Dog : public Animal {
public:
    void speak() {
        [1]::speak();
        std::cout << "Woof!" << std::endl;
    }
};
Drag options to blanks, or click blank then click option'
ADog
BBase
CAnimal
DParent
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using the derived class name instead of the base class name.
Using incorrect class names like Base or Parent.
4fill in blank
hard

Fill both blanks to create a constructor in the derived class Cat that calls the base class constructor with a name parameter.

C++
class Cat : public Animal {
public:
    Cat(std::string [1]) : [2]([1]) {}
};
Drag options to blanks, or click blank then click option'
Aname
BAnimal
CDog
DCat
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using different names for the parameter and argument.
Calling the wrong class constructor.
5fill in blank
hard

Fill all three blanks to override the speak() method in the derived class Bird and call the base class speak() method.

C++
class Bird : public [1] {
public:
    void speak() override {
        [2]::[3]();
        std::cout << "Tweet!" << std::endl;
    }
};
Drag options to blanks, or click blank then click option'
AAnimal
BBird
Cspeak
DDog
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using the derived class name instead of the base class name.
Using incorrect method names.