In: Computer Science
In a header file Record.h, create a Record structure that contains the following information: recordID, firstName, lastName, startYear. recordID is an integer.
In testRecord, first create a record (record1) using “normal” pointers. Set the values to 1001, Fred, Flintstone, 1995
In testRecord, create a new record (record2) using a unique smart pointer. Set the values to 1002, Barney, Rubble, 2000
Create a function (or functions) that will print the records to any output stream. Since the print function does not need to change the record, pass record2 as a constant. Print the records.
Create a function (or functions) that will set the year value of an already created record1 or record2 to the current value minus 10. Print the records.
1). ANSWER :
GIVENTHAT :
Record.h
#include <string>
struct Record
{
int recordID,startYear;
std::string firstName,lastName;
};
testRecord.cpp
#include <iostream>
#include <memory>
#include "Record.h"
using namespace std;
unique_ptr<Record> print(unique_ptr<Record> r)
//function to print details of unique pointer of Record
{
cout << "ID: " << r->recordID << endl;
cout << "First Name: " << r->firstName <<
endl;
cout << "Last Name: " << r->lastName <<
endl;
cout << "Starting Year: " << r->startYear <<
endl;
return r;
}
void print(Record *r) //function to print details of normal
pointer of Record
{
cout << "ID: " << r->recordID << endl;
cout << "First Name: " << r->firstName <<
endl;
cout << "Last Name: " << r->lastName <<
endl;
cout << "Starting Year: " << r->startYear <<
endl;
}
unique_ptr<Record> change(unique_ptr<Record> r)
//function to change year of unique pointer of Record
{
r->startYear-=10;
return r;
}
void change(Record *r) //function to change year of normal
pointer of Record
{
r->startYear-=10;
}
int main()
{
//testing the functions
Record *r1=new Record; //dynamically allocating pointer
r1->recordID=1001;
r1->firstName="Fred";
r1->lastName="Flintstone";
r1->startYear=1995;
unique_ptr<Record> r2(new Record); //dynamically allocating
unique pointer
r2->recordID=1002;
r2->firstName="Barney";
r2->lastName="Rubble";
r2->startYear=2000;
cout << "Normal pointer before changing: " <<
endl;
print(r1);
change(r1);
cout << "Normal pointer after changing: " <<
endl;
print(r1);
cout << "Smart Unique pointer before changing: " <<
endl;
r2=print(move(r2));
r2=change(move(r2));
cout << "Smart Unique pointer after changing: " <<
endl;
r2=print(move(r2));
return 0;
}
The above program Output: