Book Class with Title, Author, and Price Attributes in C++

This C++ exercise focuses on implementing a class named Book that encapsulates the basic details of a book, including its title, author, and price. The objective is to demonstrate how to define a class with multiple data members, utilize constructors, and display object information using member functions. This task is ideal for learners who want to reinforce their understanding of class design, constructors, and method usage in C++. By the end of this exercise, you will be able to model a simple book object and interact with its data in a structured way.

Group

Object-Oriented Programming in C++

Objective

1. Define a class named Book with private attributes: title, author, and price.
2. Create a constructor that initializes these attributes.
3. Implement a method named displayInfo that prints the book’s title, author, and price.
4. In the main function, create an instance of the Book class and call the displayInfo method to show the stored information.

Create a Book class that includes attributes like title, author, and price.

Example C++ Exercise

 Copy C++ Code
#include <iostream>     // Include input-output stream for console interaction
#include <string>       // Include string library to use string data type
using namespace std;

// Define the Book class
class Book {
private:
    string title;       // Variable to store the title of the book
    string author;      // Variable to store the author's name
    double price;       // Variable to store the price of the book

public:
    // Constructor to initialize all attributes of the Book
    Book(string t, string a, double p) {
        title = t;
        author = a;
        price = p;
    }

    // Method to display the book's information
    void displayInfo() {
        cout << "Book Title: " << title << endl;
        cout << "Author: " << author << endl;
        cout << "Price: $" << price << endl;
    }
};

int main() {
    // Create an object of the Book class with sample data
    Book myBook("The Great Gatsby", "F. Scott Fitzgerald", 12.99);

    // Display the book's details
    myBook.displayInfo();

    return 0;   // End of the program
}

 Output

Book Title: The Great Gatsby
Author: F. Scott Fitzgerald
Price: $12.99

Share this C++ Exercise


More C++ Programming Exercises of Object-Oriented Programming in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.