Lesson 6 of 6
Practice & Quiz - OOP Part II
Test your knowledge of inheritance, virtual functions, vtable, abstract classes, and the diamond problem with a practical exercise and 5 quiz questions.
Practical Exercise - Polymorphic Animal Sounds
#include <iostream>
#include <vector>
#include <memory>
#include <string>
class Animal {
std::string name_;
public:
explicit Animal(std::string name) : name_(std::move(name)) {}
virtual ~Animal() = default;
virtual std::string sound() const = 0; // pure virtual - abstract class
virtual std::string type() const = 0;
// Non-virtual: stable interface calling virtual hooks
void introduce() const {
std::cout << type() << " named " << name_
<< " says: " << sound() << "\n";
}
const std::string& name() const { return name_; }
};
class Dog final : public Animal {
public:
explicit Dog(std::string name) : Animal(std::move(name)) {}
std::string sound() const override { return "Woof!"; }
std::string type() const override { return "Dog"; }
};
class Cat : public Animal {
public:
explicit Cat(std::string name) : Animal(std::move(name)) {}
std::string sound() const override { return "Meow!"; }
std::string type() const override { return "Cat"; }
};
class Kitten final : public Cat {
public:
explicit Kitten(std::string name) : Cat(std::move(name)) {}
std::string sound() const override { return "Mew!"; }
std::string type() const override { return "Kitten"; }
};
int main() {
// Polymorphic container - unique_ptr for safe ownership
std::vector<std::unique_ptr<Animal>> zoo;
zoo.push_back(std::make_unique<Dog>("Rex"));
zoo.push_back(std::make_unique<Cat>("Whiskers"));
zoo.push_back(std::make_unique<Kitten>("Tiny"));
for (const auto& a : zoo) a->introduce();
// dynamic_cast - safe downcast
for (const auto& a : zoo) {
if (const Dog* d = dynamic_cast<const Dog*>(a.get())) {
std::cout << d->name() << " is a dog!\n";
}
}
return 0;
}Module Quiz
What does `override` keyword do in C++11?
Tip
Tip
Practice Practice Quiz OOP Part II in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Inheritance Modes, Virtual Dispatch, vtables, Abstract Interfaces & Diamond Problem Resolution
Practice Task
Note
Practice Task - (1) Write a working example of Practice Quiz OOP Part II from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Practice Quiz OOP Part II is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Finished this lesson?