CodeBlanks Logo Icon CodeBlanks

Model design

Design the skeleton of Book and Member classes.

Project: Library app

In this 5-lesson project you will build a library application. Each lesson adds one piece, and by the final lesson you will have a working console app. Everything is built on the Book and Library classes.

You will use what you learned in previous groups: classes, constructors and iterators. In the first lesson you design the Book class skeleton: title and author fields are private, and getTitle() exposes them to callers. The starting code of the next lessons will contain this class.

Book class design

The Book class carries two private fields: title and author. The constructor (Book(std::string t, std::string a)) initializes them. The getTitle() and getAuthor() methods let callers read the values.

Example: Book b("Tutunamayanlar", "Oğuz Atay"); creates a book. b.getTitle() reads the title. The member initializer list (: title(t), author(a)) initializes fields efficiently. const methods do not modify the class; that is why getters are const.

Practice Define the Book class

Define a Book class. In the private section add std::string title and std::string author fields. In the public section add a constructor and a getTitle() method. In main, create a Book and print its title with std::cout.

Starter code

main.cpp
#include <iostream>
#include <string>

// Define the Book class here

int main() {
    // Create a Book and print its title
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <string>

class Book {
private:
    std::string title;
    std::string author;
public:
    Book(std::string t, std::string a) : title(t), author(a) {}
    std::string getTitle() const { return title; }
    std::string getAuthor() const { return author; }
};

int main() {
    Book b("Tutunamayanlar", "Oğuz Atay");
    std::cout << b.getTitle();
    return 0;
}

Expected output

Tutunamayanlar

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which member should be private?

main.cpp
class Book {
    ???
    std::string title;
};
  • the getTitle method
  • the main function
  • the title field Correct answer
  • std::cout

Explanation: Data fields are private, accessor methods are public.

2 Call the getter method

Question
Book b("Tutunamayanlar", "Oğuz Atay");
std::cout << b.____();
Answer
Book b("Tutunamayanlar", "Oğuz Atay");
std::cout << b.getTitle();

Explanation: b.getTitle() reads the title.

3 Match each member to its role

Term Meaning
std::string title Private data
Book(std::string, std::string) Constructor
std::string getTitle() Getter method
const No-modify marker

All lessons in Intermediate