Kat H.

asked • 07/07/21

Car Class with Dynamic Memory

What To Code


With your Car class from previous code:


1. Rewrite the C string members (make and model) to be dynamic C strings.


Make all C strings the length of any passed in C string.


NOTE: The other variables (including temporary C strings used only in functions) don't need to be made dynamic.


2. Write a destructor for this class that deletes the dynamic C-Strings.


3. Write a public member function called 'print' that prints out the make, model and year values.


Use carmain2.cpp to test your class. note that it passes in constant C strings so make your class setters take a const C string:


void setMake(const char *mk);


and also make the getters' return type a constant:


const char * getMake();


Requirements


Must have dynamic C-Strings as member variables in your Car class. No static C strings or string type variables.


• Must have a destructor for your class.


• Must have 2files: car.h and car.cpp


• No function definitions in the car.h file.


EXAMPLE OUTPUT #1

--------------------------------

Sedan before initialization:
make: <no value set>
model: <no value set>
year: 0
Compact values
Make: Honda
Model: Civic
Year: 2017
Setting values for sedan:
Enter make: Ford
Enter model: Escort
Enter year: 1997
printing values for sedan:
Make: Ford
Model: Escort
Year: 1997


carmain2.cpp:


#include "car.h"

#include<iostream>

using namespace std;


int main()

{

  Car sedan;


// input

string imake;

string imodel;

int iyear;


// output

string omake;

string omodel;

int oyear;


// getting values before setting them.

// This may produce garbage values. We will be

// fixing this in exercise 2.

cout << "Sedan before initialization: " << endl;

omake = sedan.getMake();

cout << "Make: " << omake << endl;


omodel = sedan.getModel();

cout << "Model: " << omodel << endl;


oyear = sedan.getYear();

cout << "Year: " << oyear << endl;


//set the values for sedan

cout << "Setting values for sedan: " << endl;

cout << "Enter make: ";

getline(cin, imake);

sedan.setMake(imake);


cout << "Enter model: ";

getline(cin, imodel);

sedan.setModel(imodel);


cout << "Enter year: ";

cin >> iyear;

cin.ignore(200, '\n');

sedan.setYear(iyear);


// getting the data back out

cout << "printing values for sedan: " << endl;

omake = sedan.getMake();

cout << "Make: " << omake << endl;


omodel = sedan.getModel();

cout << "Model: " << omodel << endl;


oyear = sedan.getYear();

cout << "Year: " << oyear << endl;


return 0;

}

1 Expert Answer

By:

Patrick B. answered • 07/08/21

Tutor
4.7 (31)

Math and computer tutor/teacher

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.