Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Constructor Delegation | Constructors and Destructors
C++ OOP

bookChallenge: Constructor Delegation

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

solution.cpp

solution.cpp

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 2. ChapterΒ 6
single

single

Ask AI

expand

Ask AI

ChatGPT

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

close

Awesome!

Completion rate improved to 3.13

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

solution.cpp

solution.cpp

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Β 2. ChapterΒ 6
single

single

some-alt