Objective: Write a C++ Program to design a class of multiple constructors.
Code:
#include <iostream>
#include <string>
using namespace std;
class Book
{
private:
string title;
string author;
int publicationYear;
public:
// Default constructor
Book()
{
title = "Unknown";
author = "Unknown";
publicationYear = 0;
}
// Parameterized constructor with title and author
Book(const string& t, const string& a)
{
title = t;
author = a;
publicationYear = 0;
}
// Parameterized constructor with title, author, and publication year
Book(const string& t, const string& a, int y)
{
title = t;
author = a;
publicationYear = y;
}
// Function to display book details
void display() const
{
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
cout << "Publication Year: " << publicationYear << endl;
}
};
int main()
{
// Create objects using different constructors
// Using the default constructor
Book book1;
cout << "Book 1 Details:" << endl;
book1.display();
// Using the constructor with title and author
Book book2("2017", "Web Tech-1");
cout << "\nBook 2 Details:" << endl;
book2.display();
// Using the constructor with title, author, and publication year
Book book3("Web Tech-2", "G Krishna", 2018);
cout << "\nBook 3 Details:" << endl;
book3.display();
return 0;
}
Output:
No comments:
Post a Comment