In: Computer Science
C++ Assignment
1) Write a C++ program specified below:
a) Include a class called Movie. Include the following attributes with appropriate types:
i. Title
ii. Director
iii. Release Year
iv. Rating (“G”, “PG”, “PG-13”, etc)
- Write code that instantiates a movie object using value semantics as text:
- Write code that instantiates a movie object using reference semantics:
- Write the print_movie method code:
- Write Constructor code:
- Write Entire Movie class declaration
We first define the class attributes(Title, director, etc) in the private part of the class. You can also define it in public section but it's a good practice to keep our attributes in private. Next, in our public section, we define 2 class constructors. The first one is a parameterised constructor in which we pass values of each attribute. The second is a Copy Constructor in which a reference of the object of the Movie class is passed to the constructor. After that, we define the print function which just prints the class attributes. In the main function we can see how to initialise the objects using different constructors.
Source Code:
#include <iostream>
using namespace std;
// Class Definition
class Movie {
// Data members of class defined in private
section
string Title;
string Director;
int ReleaseYear;
string Rating;
public:
// Parameterised constructor for the class
Movie(string title, string director, int releaseYear,
string rating) {
cout << "Parameterised
Constructor Called!" << endl;
Title = title;
Director = director;
ReleaseYear = releaseYear;
Rating = rating;
}
// Copy Constructor of the class
Movie(Movie &obj) {
cout << "Copy Constructor
Called!" << endl;
Title = obj.Title;
Director = obj.Director;
ReleaseYear =
obj.ReleaseYear;
Rating = obj.Rating;
}
// Method that prints the data of the object
void print_movie() {
cout << "Title: " <<
Title << endl;
cout << "Director: " <<
Director << endl;
cout << "Release Year "
<< ReleaseYear << endl;
cout << "Rating: " <<
Rating << endl;
}
};
int main() {
// Creating our first object using value
sematics
Movie movie1("Avengers", "Russo Brothers", 2019,
"PG-13");
// Printing the values of our object
movie1.print_movie();
cout << "==========" << endl;
// Creating the second object. Here the copy
constructor is called
Movie movie2 = movie1;
// Printing its data
movie2.print_movie();
return 0;
}