Embercode
✕
Object-Oriented ProgrammingQuick quiz

Slicing and Object

7 questions. Covers Object slicing and the Object class.

Questions 1 to 5 of 7

  1. 1. What does this program print? ``cpp #include <iostream> #include <string> struct Animal { std::string name = "unnamed"; virtual ~Animal() = default; virtual std::string sound() const { return "..."; } }; struct Dog : Animal { std::string breed = "mixed"; std::string sound() const override { return "Woof " + breed; } }; int main() { Dog d; d.name = "Ace"; d.breed = "Pug"; Animal a = d; Animal& r = d; std::cout << a.name << ": " << a.sound() << "\n"; std::cout << r.name << ": " << r.sound() << "\n"; } ``
  2. 2. Why does a by-value Animal parameter slice a Dog argument?
  3. 3. Which standard smart pointer has exactly one owner and deletes its object when that owner goes away? The lesson uses it to keep each whole Dog in a vector of Animal pointers.

    Type your answer.

  4. 4. What does this program print? ``cpp #include <iostream> #include <memory> #include <string> #include <vector> struct Animal { std::string name = "unnamed"; virtual ~Animal() = default; virtual std::string sound() const { return "..."; } }; struct Dog : Animal { std::string breed = "mixed"; std::string sound() const override { return "Woof " + breed; } }; void show_value(Animal a) { std::cout << a.sound() << "\n"; } void show_ref(const Animal& a) { std::cout << a.sound() << "\n"; } int main() { Dog d; d.breed = "Beagle"; show_value(d); show_ref(d); std::vector<Animal> values; values.push_back(d); std::cout << values[0].sound() << "\n"; std::vector<std::unique_ptr<Animal>> owned; owned.push_back(std::make_unique<Dog>(d)); std::cout << owned[0]->sound() << "\n"; } ``
  5. 5. Statement: C++ gives every class a default == that compares its fields, so a == b compiles with no code written in the class.

5 question(s) left on this page.

Typed answers ignore extra spaces and, for most questions, capital letters.