Solved Practicals
OOP
Topic:Understanding Classes, Objects, Constructors, and Data
Encapsulation
Question 4:
Problem:
Create a class Book that encapsulates the following data members:
title, author, and price. Use a constructor to initialize these fields.
Include a method displayDetails() that prints out the book details.
Demonstrate usage by creating two Book objects.
Solution (C++):
cpp
CopyEdit
#include <iostream>
#include <string>
using namespace std;
class Book {
private:
string title;
string author;
float price;
public:
// Constructor
Book(string t, string a, float p) {
title = t;
author = a;
price = p;
}
// Method to display book details
void displayDetails() {
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
cout << "Price: $" << price << endl << endl;
}
};
int main() {
Book book1("1984", "George Orwell", 15.99);
Book book2("To Kill a Mockingbird", "Harper Lee", 12.50);
book1.displayDetails();
book2.displayDetails();
return 0;
}