Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Constructor Delegation | Introduction
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
C++ Classes and Objects
Sectionย 1. Chapterย 14
single

single

bookChallenge: Constructor Delegation

Swipe to show menu

Task

Swipe to start coding

Imagine you are creating a library management system. You need to build a Book class that can be initialized in different ways using constructor delegation. Your task is to implement multiple constructors that call each other to avoid code duplication, and a method to display book information.

  1. Implement constructors using delegation:
    • A constructor with title, author, and year.
  • A constructor with title and author only; sets year to 0.
  • A constructor with title only; sets author to "Unknown" and year to 0.
  1. Implement a method printInfo that prints the book information in the format:
    "Title: <title>, Author: <author>, Year: <year>"

Example

Book("1984", "George Orwell", 1949) โ†’ Title: 1984, Author: George Orwell, Year: 1949

Book("Clean Code", "Robert C. Martin") โ†’ Title: Clean Code, Author: Robert C. Martin, Year: 0

Book("Mystery Book") โ†’ Title: Mystery Book, Author: Unknown, Year: 0

Book() โ†’ Title: Undefined, Author: Unknown, Year: 0

Solution

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Sectionย 1. Chapterย 14
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt