LearnFrenzy
Sign in Take a free test

Abstract Classes and Interfaces · Find the Error · Question 1

Error: new on an abstract class Answer, explanation & discussion

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

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

main.cpp
#include <iostream>

struct Animal {
    virtual const char* sound() const = 0;
    virtual ~Animal() = default;
};
struct Cat : Animal { const char* sound() const override { return "Meow"; } };

int main() {
    Animal* a = new Animal;
    std::cout << a->sound() << '\n';
    delete a;
    return 0;
}
  • A sound must not be const
  • B Animal is abstract (sound is pure virtual), so new Animal is not allowed; create a concrete class such as new Cat Correct
  • C delete cannot be used with Animal*
  • D Cat must be declared before Animal
Correct Answer: Option B

A pointer of type Animal* is fine – it just has to point to a concrete object.

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