0
0
C++programming~30 mins

Object interaction in C++ - Mini Project: Build & Apply

Choose your learning style9 modes available
Object interaction
πŸ“– Scenario: You are creating a simple program to manage a library. The library has books, and each book has a title and an author. You want to show how two objects, Library and Book, can work together.
🎯 Goal: Build two classes, Book and Library, where the Library holds a list of Book objects. You will add books to the library and then print the details of all books in the library.
πŸ“‹ What You'll Learn
Create a class Book with two public string members: title and author.
Create a class Library with a public vector of Book objects called books.
Add a method addBook to Library that takes a Book object and adds it to books.
Add a method printBooks to Library that prints all books with their titles and authors.
In main(), create a Library object, add two Book objects with exact titles and authors, then print all books.
πŸ’‘ Why This Matters
🌍 Real World
Managing collections of objects is common in software like libraries, stores, or contact lists. This project shows how objects can hold and manage other objects.
πŸ’Ό Career
Understanding object interaction is key for software development jobs, especially when designing systems with multiple related data types.
Progress0 / 4 steps
1
Create the Book class
Create a class called Book with two public string members: title and author. Then create two Book objects named book1 and book2 with these exact values: book1.title = "1984", book1.author = "George Orwell", book2.title = "To Kill a Mockingbird", book2.author = "Harper Lee".
C++
Need a hint?

Define the Book class with two public string variables. Then create two Book objects and assign the exact titles and authors.

2
Create the Library class with a vector of books
Add a class called Library with a public vector<Book> member named books. Include #include <vector> at the top. In main(), create a Library object named library.
C++
Need a hint?

Include the vector header. Define Library with a public vector of Book. Then create a Library object in main().

3
Add addBook method to Library
Add a public method addBook to the Library class that takes a Book parameter named book and adds it to the books vector using push_back. In main(), call library.addBook(book1) and library.addBook(book2).
C++
Need a hint?

Define addBook inside Library to add a Book to the books vector. Then call it twice in main().

4
Add printBooks method and print all books
Add a public method printBooks to Library that uses a for loop with variables book to iterate over books and prints each book's title and author in the format: Title: [title], Author: [author]. In main(), call library.printBooks().
C++
Need a hint?

Use a for loop to go through each Book in books and print the title and author. Then call printBooks() in main().