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
Show 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