Question

In: Computer Science

Data Structures Use good style. Make sure that you properly separate code into .h/.cpp files. Make...

Data Structures

Use good style. Make sure that you properly separate code into .h/.cpp files. Make sure that you add preprocessor guards to the .h files to allow multiple #includes.

Overview

You will be writing the classes Grade and GradeCollection. You will be writing testing code for the Grade and GradeCollection classes.

Part 1 – Create a Grade Class

Write a class named Grade to store grade information.

Grade Class Specifications

  1. Include member variables for name (string), score (double).
  2. Write a default constructor.
  3. Write a constructor that takes values for all member variables as parameters.
  4. Write a copy constructor.
  5. Implement Get/Set methods for all member variables.
  6. Add a member overload for the assignment operator.
  7. Add a non-member operator<< overload. Prints the values of all member variables on the given ostream.  

Part 2 – Create a GradeCollection Class

Write a class that will store a collection of Grade. This class will be used to keep track of data for multiple grades. You MUST implement ALL of the specifications below.

GradeCollection Class Specifications

  1. Create a private member variable that is an array of Grade. The size of the array can be whatever you want it to be.
  2. Your class must implement all of the following functions (use the given function prototypes):
    1. Create a default constructor that will initialize all elements of the array to default values.
    2. void Set(int index, Grade g) – Sets the value at the given index to the given Grade. You should test the index to make sure that it is valid. If the index is not valid then do not set the value.
    3. Grade Get(int index) – Return the Grade located at element index of the array.
    4. int GradeCount(double lowerBound, double upperBound) – Returns the count of the number of grades in the given range. For example, assume the following scores: 60, 70, 65, 75, 80, 90

If lowerBound is 70 and upperBound is 80 then the returned value should be 3. Any values that fall on the boundaries should be included in the count.

  1. Grade LowestGrade() – Returns the grade with the lowest score in the array.
  2. bool FindGrade(string name, Grade &g) – Returns true if the grade with the given name is in the array and false otherwise. If the grade is in the array you should copy it into the Grade reference parameter.
  3. double GradeAverage() – Returns the average of all the grades in the collection
  4. int Size() – Returns the size of the array.
  5. void Initialize() – Initializes all of the elements of the array to reasonable default values.
  6. string GetAuthor() – Returns your name. Just hard code your name into the function.

Part 3 – Main Function

In main you should create instances of the Grade and GradeCollection classes and demonstrate that ALL functions work properly on both classes. You can write unit testing code if you want but you are not required to. Make sure you call ALL functions.

Part 4 – Comments

In addition to the normal comments, EVERY function that gets updated because of the required changes should have an update comment added to the function commenting header. The update comment should have your name, the date of the change, and a short description of the change. For example:

//****************************************************

// Function: SetName

//

// Purpose: Sets the name of the grade.

//

// Update Information

// ------------------

//

// Name:

// Date: 9/20/2016

// Description: mName member variable was changed to a

//              pointer. Updated code so that it works //              with a pointer.

//

//****************************************************

Part 5 – Updated Grade and GradeCollection Classes

Grade Class Updates

The Grade class should implement all the specifications from the first assignment plus the updates and features listed below.

  1. Change all member variables to pointers. You will need to update code in any functions that use these member variables. Do NOT change any function signatures for this class. For example, assume the get/set functions have the following signatures:

std::string GetName(); void SetName(std::string name);

These signatures should remain exactly the same. The same goes for any other functions that use these member variables. Only the internal implementation of the functions will change to accommodate the use of pointers.

  1. Update the constructors. The constructors should allocate memory for the pointer member variables.
  2. Add a destructor. The destructor should deallocate memory for the pointer member variables.
  3. Update operator= and copy constructor. The operator= and copy constructor should be updated to perform deep copies.
  4. Add a non-member operator>> overload. The >> operator is used for input. Reads the values of all member variables from the given istream.

GradeCollection Class Updates

The GradeCollection class should implement all the specifications from the first assignment plus the updates and features listed below.

  1. Dynamic array. Change the internal implementation of the array so that the array is dynamically allocated.
  2. Add a size member variable to the class. This member variable should ALWAYS contain the number of elements in the array (size of the array). Some functions may cause the size of the array to change so make sure that this member variable is updated to reflect the new size.
  3. Update all the necessary code in the class so that it is usable with a dynamic array. One example of this is to change the ending condition of loops that visit all elements of the array should not be hard coded. They should use the new size variable as the ending condition.
  4. Add a one parameter constructor that takes a size. This constructor should dynamically allocate an array of the given size. It should also set the size member variable to reflect the size.
  5. Add a copy constructor. This function should make a deep copy of the passed in instance.
  6. Add a destructor. This function should perform any necessary cleanup.
  7. Add a member overload of operator= (assignment operator). This method should perform a deep copy of the passed in instance. After this function ends the size of the current instance’s array should be the same as the other instance’s array and all the data from the other instance should be copied into the current instance’s array. Hint: C++ arrays have a fixed size. You may need to delete and then reallocate memory for the current instance’s array in order to make the current instance’s array the same size as the other instance’s array. Be careful for memory leaks.
  8. Add a non-member operator<< overload. Prints the values of all elements of the array on the given ostream.
  9. Add a Resize function. Here is the function signature: void Resize(int newSize);

This function should create a new array that has the passed in size. You MUST retain any values that were previously in the array. The new array size can be larger or smaller. If the new array size is SMALLER just retain as many elements from the previous array that can fit.

Hint: C++ arrays have a fixed size. You may need to delete and then reallocate memory. Be careful for memory leaks.

  1. Add a function named Clone with the following signature:

GradeCollection *Clone();

This function should allocate a new dynamic instance of GradeCollection that is a deep copy of the current instance. This method should return a pointer to the new instance.

Hint: Any function that calls Clone is responsible for releasing the returned memory address.

Part 6 – Main Function

In main you should create instances of the updated Grade and GradeCollection classes and demonstrate that ALL functions work properly. You can write unit testing code if you want but you are not required to. Make sure you call ALL functions.

You program should not have memory leaks.

Solutions

Expert Solution

C++ Separate Header and Implementation Files C++ classes (and often function prototypes) are normally split up into two files. The header file has the extension of .h and contains class definitions and functions. The implementation of the class goes into the .cpp file. By doing this, if your class implementation doesn’t change then it won’t need to be recompiled. Most IDE’s will do this for you – they will only recompile the classes that have changed. This is possible when they are split up this way, but it isn’t possible if everything is in one file (or if the implementation is all part of the header file). Simple example: File: Num.h class Num { private: int num; public: Num(int n); int getNum(); }; File: Num.cpp #include "Num.h" Num::Num() : num(0) { } Num::Num(int n): num(n) {} int Num::getNum() { return num; } File: main.cpp #include #include "Num.h" using namespace std; int main() { Num n(35); cout #include "Num.h" #include "Foo.h" using namespace std; int main() { Num n(35); cout #endif This says if “NUM_H” is not defined, then define it. So subsequent attempts to read this class result in skipping the definition since NUM_H is already defined. If we add this to our Num.h class then it will now compile and run. You can use any name but the recommendation is to use a name related to the class. The #pragma once directive The same functionality as #ifndef can be accomplished by adding #pragma once to the top of your file. This is the default used with Visual Studio. Separate Compilation With what we’ve done so far we split the header from the implementation. We’re actually still compiling both all the time though when we run the g++ command. To really get separate compilation we need to: 1. Compile each .cpp file into an object file, which contains machine code for that file 2. Link each object file into an executable To compile into an object file, you can use the command flag of –c: g++ -c main.cpp Num.cpp This produces a file main.o and Num.o. We can then link them. We can use g++ again to do this: g++ main.o Num.o We now have our familiar a.out program which we can run. An efficiency step is possible here because if Num never changes but main does change, then we can compile just main via: g++ -c main.cpp Then we can link them again but we didn’t have the overhead of compiling Num.cpp: g++ main.o Num.o With our little programs this saves virtually no time, but for really large programs this can be a significant savings in compile time. All of this stuff is done for you automatically by an IDE (which is one reason why they are great). The make utility It can also be a pain to compile lots of files when you have a big project. Once again, this functionality is provided for you as part of an IDE. But you have to do it yourself if you are compiling from the command line. Well, there is a solution in the make utility. If you run the command “make” then this program will look for a file named “Makefile” that contains information about program dependencies and what needs to be compiled. Here is an example for our particular setup: CFLAGS = -O CC = g++ NumTest: main.o Num.o $(CC) $(CFLAGS) -o NumTest main.o Num.o main.o: main.cpp $(CC) $(CFLAGS) -c main.cpp Num.o: Num.cpp $(CC) $(CFLAGS) -c Num.cpp clean: rm -f core *.o This says that NumTest depends on main.o and Num.o and the second line says how to compile it. In turn, main.o is created by compiling main.cpp with the –c flag. We can compile by typing: make or make NumTest We can use the target of “clean” to delete object files and core dumps. Only files that have changed are recompiled. Here is a similar version using some more advanced features of Makefiles: CFLAGS = -O CC = g++ SRC = main.cpp Num.cpp OBJ = $(SRC:.cpp = .o) NumTest: $(OBJ) $(CC) $(CFLAGS) -o NumTest $(OBJ) clean: rm -f core *.o


Related Solutions

Separate code into .cpp and .h files: // C++ program to create and implement Poly class...
Separate code into .cpp and .h files: // C++ program to create and implement Poly class representing Polynomials #include <iostream> #include <cmath> using namespace std; class Poly { private: int degree; int *coefficients; public: Poly(); Poly(int coeff, int degree); Poly(int coeff); Poly(const Poly& p); ~Poly(); void resize(int new_degree); void setCoefficient(int exp, int coeff); int getCoefficient(int exp); void display(); }; // default constructor to create a polynomial with constant 0 Poly::Poly() { // set degree to 0 degree = 0; //...
Complete the following task in C++. Separate your class into header and cpp files. You can...
Complete the following task in C++. Separate your class into header and cpp files. You can only useiostream, string and sstream. Create a main.cpp file to test your code thoroughly. Given : commodity.h and commodity.cpp here -> https://www.chegg.com/homework-help/questions-and-answers/31-commodity-request-presented-two-diagrams-depicting-commodity-request-classes-form-basic-q39578118?trackid=uF_YZqoK Create : locomotive.h, locomotive.cpp, main.cpp Locomotive Class Hierarchy Presented here will be a class diagram depicting the nature of the class hierarchy formed between a parent locomotive class and its children, the two kinds of specic trains operated. The relationship is a...
Complete the following task in C++. Separate your class into header and cpp files. You can...
Complete the following task in C++. Separate your class into header and cpp files. You can only use iostream, string and sstream. Create a main.cpp file to test your code thoroughly. Given : commodity.h and commodity.cpp here -> https://www.chegg.com/homework-help/questions-and-answers/31-commodity-request-presented-two-diagrams-depicting-commodity-request-classes-form-basic-q39578118?trackid=uF_YZqoK Given : locomotive.h, locomotive.cpp, main.cpp -> https://www.chegg.com/homework-help/questions-and-answers/complete-following-task-c--separate-class-header-cpp-files-useiostream-string-sstream-crea-q39733428 Create : DieselElectric.cpp DieselElectric.h DieselElectric dieselElectric -fuelSupply:int --------------------------- +getSupply():int +setSupply(s:int):void +dieselElectric(f:int) +~dieselElectric() +generateID():string +calculateRange():double The class variables are as follows: fuelSuppply: The fuel supply of the train in terms of a number of kilolitres...
Code the following in C++ and make sure to include all three files required at the...
Code the following in C++ and make sure to include all three files required at the end. Hotdogs – The World’s Greatest Cost Effective Wholesome Nutritious Food Due to world food supply scarcity and the burgeoning populations of the world’s countries, your hot stand business is globalizing to satisfy the world’s desire for a cost effective wholesome nutritious food source. Market studies have shown that tens of billions of people are craving for the eponymous hotdog which will result in...
<<Importing Data>> Make sure you have downloaded all the data files off Blackboard. There should be...
<<Importing Data>> Make sure you have downloaded all the data files off Blackboard. There should be folders containing images and audio files as well as a selection of CSV and Excel spreadsheets. The following exercises will allow you to practice using MATLAB’s import/export functions. Task 4 – Importing Excel Spreadsheets Exercise: Import the spreadsheet ‘buildings.xls’ which contains all the buildings in the world over 300 metres tall. Plot the number of floors vs. building height using a scatter plot. Reflection:...
In C++ You will create 3 files: The .h (specification file), .cpp (implementation file) and main...
In C++ You will create 3 files: The .h (specification file), .cpp (implementation file) and main file. You will practice writing class constants, using data files. You will add methods public and private to your BankAccount class, as well as helper methods in your main class. You will create an arrayy of objects and practice passing objects to and return objects from functions. String functions practice has also been included. You have been given a template in Zylabs to help...
BankAccount: You will create 3 files: The .h (specification file), .cpp (implementation file) and main file....
BankAccount: You will create 3 files: The .h (specification file), .cpp (implementation file) and main file. You will practice writing class constants, using data files. You will add methods public and private to your BankAccount class, as well as helper methods in your main class. You will create an array of objects and practice passing objects to and return objects from functions. String functions practice has also been included. Extend the BankAccount class. The member fields of the class are:...
use repil.it intro to C-programin be sure Make code very basic and add good comments thank...
use repil.it intro to C-programin be sure Make code very basic and add good comments thank you 1-Write a program that requests 5 integers from the user and stores them in an array. You may do this with either a for loop OR by getting a string from stdin and using sscanf to store formatted input in each spot in the array. 2-Add a function to the program, called get_mean that determines the mean, which is the average of the...
convert this code to Python and make sure you use chained map and filter as well....
convert this code to Python and make sure you use chained map and filter as well. https://book.pythontips.com/en/latest/map_filter.html CODE BELOW IS IN JAVASCRIPT let people = [ {name: "Amy", pounds_weight: 152, inches_height: 63}, {name: "Joe", pounds_weight: 120, inches_height: 64}, {name: "Tom", pounds_weight: 210, inches_height: 78}, {name: "Jim", pounds_weight: 180, inches_height: 68}, {name: "Jen", pounds_weight: 120, inches_height: 62}, {name: "Ann", pounds_weight: 252, inches_height: 63}, {name: "Ben", pounds_weight: 240, inches_height: 72}, ]; //functions to convert pounds to kg and inches to meters let...
In order to make sure that all math formatting is properly displayed, you are strongly encouraged...
In order to make sure that all math formatting is properly displayed, you are strongly encouraged to reload this page after opening. In order to make sure that all math formatting is properly displayed, you are strongly encouraged to reload this page after opening.   Consider the following statistical studies. Which method of data collection would likely be used to collect data for each study? Explain your selection. What is the population of interest? Would you take a census or use...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT