LearnFrenzy
Sign in Take a free test

Constructors and Destructors · Find the Error · Question 7

Error: delegating constructor that also initializes a member Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

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

main.cpp
#include <iostream>

class Range {
    int lo_, hi_;
public:
    Range(int lo, int hi) : lo_(lo), hi_(hi) {}
    Range(int hi) : Range(0, hi), lo_(1) {}
    int size() const { return hi_ - lo_; }
};

int main() {
    Range r(10);
    std::cout << r.size() << '\n';
    return 0;
}
  • A Range needs a default constructor
  • B A delegating constructor's initializer list may contain only the delegation – it cannot also initialize members such as lo_ Correct
  • C size must not be const
  • D hi must be unsigned
Correct Answer: Option B

The target constructor initializes everything. Change values in the body if needed, or delegate with different arguments: Range(int hi) : Range(1, hi) {}.

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