Challenge: Constructor Delegation
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.
- Implement constructors using delegation:
- A constructor with
title,author, andyear.
- A constructor with
- A constructor with
titleandauthoronly; setsyearto0. - A constructor with
titleonly; setsauthorto"Unknown"andyearto0.
- Implement a method
printInfothat 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
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Awesome!
Completion rate improved to 3.13
Challenge: Constructor Delegation
Swipe to show menu
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.
- Implement constructors using delegation:
- A constructor with
title,author, andyear.
- A constructor with
- A constructor with
titleandauthoronly; setsyearto0. - A constructor with
titleonly; setsauthorto"Unknown"andyearto0.
- Implement a method
printInfothat 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
Thanks for your feedback!
single