0% found this document useful (0 votes)
23 views2 pages

Solved Practical Part2 OOP

The document presents a practical exercise in Object-Oriented Programming (OOP) by creating a class named Book. It encapsulates attributes such as title, author, and price, and includes a constructor for initialization along with a method to display book details. The solution demonstrates the creation of two Book objects and their details are printed using the displayDetails() method.

Uploaded by

zainzeeshan192
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views2 pages

Solved Practical Part2 OOP

The document presents a practical exercise in Object-Oriented Programming (OOP) by creating a class named Book. It encapsulates attributes such as title, author, and price, and includes a constructor for initialization along with a method to display book details. The solution demonstrates the creation of two Book objects and their details are printed using the displayDetails() method.

Uploaded by

zainzeeshan192
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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;
}

You might also like