Untitled

 avatar
unknown
plain_text
5 months ago
1.2 kB
3
Indexable
#include <iostream>
#include <cstring>
using namespace std;
class Book {
private:
char *title;
int pages;
float price;
public:
// Default Constructor
Book() {
title = new char[1];
title[0] = '\0'; // Empty string
pages = 0;
price = 0.0;
}
// Parameterized Constructor
Book(const char *t, int p, float pr) {
title = new char[strlen(t) + 1];
strcpy(title, t);
pages = p;
price = pr;
}
// Copy Constructor
Book(const Book &b) {
title = new char[strlen(b.title) + 1];
strcpy(title, b.title);
pages = b.pages;
price = b.price;
}
// Destructor to release dynamically allocated memory
~Book() {
delete[] title;
}
// Display function to show book details
void display() {
cout << "Title: " << title << endl;
cout << "Pages: " << pages << endl;
cout << "Price: $" << price << endl;
}
};
int main() {
// Using Default Constructor
Book book1;
cout << "Book 1 (Default Constructor):" << endl;
book1.display();
// Using Parameterized Constructor
Book book2("The C++ Programming Language", 1350, 59.99);
cout << "\nBook 2 (Parameterized Constructor):" << endl;
book2.display();
// Using Copy Constructor
Book book3 = book2;
cout << "\nBook 3 (Copy Constructor):" << endl;
book3.display();
return 0;
}
Editor is loading...
Leave a Comment