LearnFrenzy
Sign in Take a free test

Inheritance · Find the Error · Question 3

Error: base class without a default constructor Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#include <iostream>
#include <string>

class Animal {
protected:
    std::string name_;
public:
    explicit Animal(std::string n) : name_(std::move(n)) {}
};

class Dog : public Animal {
public:
    Dog() { name_ = "Bruno"; }
};

int main() {
    Dog d;
    return 0;
}
  • A name_ must be public
  • B Animal has no default constructor, and Dog's constructor does not call Animal(std::string) in its initializer list; write Dog() : Animal("Bruno") {} Correct
  • C Dog must be a struct
  • D Strings cannot be protected
Correct Answer: Option B

The base is constructed before the derived constructor's body runs, so the base constructor must be chosen in the initializer list.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links