Static vector as a class objects container - c++

I've seen many questions and answers about this issue but still I can't solve my problem. How should I initialize a static vector? I'm also asking you for checking I use a default construct properly. I don't mean checking if it's working because I know that it does. I just wonder if it is an elegant implementation?
class Employee
{
private:
static std::vector<Employee> employee;
std::string name;
int age;
Employee::Employee()
{
std::string localName;
int localAge;
std::cout << "So... do you want to hire a new employee? Let's look at CVs " << std::endl;
localName = "Marek"; //GenerateName();
localAge = 21; //these function is not ready yet. it'd be just a rand()
std::cout << "I've got one. What do u think about " << localName << " age " << localAge << "?" << std::endl;
int decision;
do
{
std::cout << "Do you want hire him [1] or not [2] ? " << std::endl;
std::cin >> decision;
switch (decision)
{
case 1:
name = localName;
age = localAge;
decision = 0;
break;
case 2:
employees.erase(employees.end());
decision = 0;
break;
default:
std::cout << "Incorrect option. Try again" << std::endl;
}
} while (decision != 0);
}
public:
static void Employ()
{
employees.push_back(Employee::Employee());
}
};
int main()
{
Employee::Employ();
system("pause");
}

Your code didn't work when I ran it. In addition to adding includes and fixing some typos, I had to add this line:
std::vector<Employee> Employee::employee;
However, I don't think this is the best solution. For sweet clarity's sake, an Employee shouldn't contain a vector of Employees, but should be, well, an employee. If you want a vector of employees, you can declare one in main (or elsewhere). If you want your vector of employees to have some added features like the interactive employee-adding function you wrote, you can do it like this:
class EmployeeForce: public std::vector<Employee>
{
void interactivelyAddEmployee ();
...
};
...
EmployeeForce myStaff;

I've changed entire the concept. The problem was that I unnecessary wanted to put inside the class the container of objects (in this case: std::vector). I know now that class should only contain informations about the single object; it shouldn't know about anything about others one.
class Employee
{
public:
std::string name;
int age;
};
std::ostream& operator<<(std::ostream& out, const std::vector<Employee>& v)
{
out << "[";
for (size_t i = 0; i < v.size(); ++i)
{
out << "Name: " << v[i].name << " age: " << v[i].age;
if (i != v.size() - 1)
out << ", ";
}
out << "]";
return out;
}
Employee generate_random_employee(Employee obj)
{
obj.name = "Marek"; //GenerateName();
obj.age = 21; //these function is not ready yet. it'd be just a rand()
return obj;
}
int main()
{
int decision;
std::string name;
std::vector<Employee> employees;
Employee some_new_employee;
std::cout << "Welcome mrs. manager. What do you want to do today, sir?" << std::endl << std::endl;
do
{
std::cout << "Hire sombody [1], Fire somebody [2], Exit [0] " << std::endl;
std::cin >> decision;
switch (decision)
{
case 1:
some_new_employee = generate_random_employee(some_new_employee);
if (should_i_employ(some_new_employee))
{
employees.push_back(some_new_employee);
}
break;
case 2:
std::cout << "Who do you want to fire?" << std::endl;
std::cin >> name;
if (is_the_employee_exist(employees, name))
{
if (are_u_sure())
{
}
}
else
std::cout << "" << std::endl;
break;
case 3:
std::cout << employees << std::endl;
break;
case 0:
std::cout << "Good bye, sir" << std::endl;
break;
default:
std::cout << "There is not these option. Try again " << std::endl;
}
} while (decision != 0);
system("pause");
}

Related

How can I use struct efficiently in my quiz?

I'm trying to create a simple quiz with struct. But my program here is very repetitive. How can I modify it and make it more efficient? Especially to check if the answers are correct I do not want to declare a separate variable and store it as int correct. Thank You.
#include <iostream>
using namespace std;
struct Quiz{
string question;
string answers[3];
};
struct Quiz2{
string question2;
string answers2[3];
};
int correct;
int main()
{
Quiz Question;
Question.question = "What is the smallest county?";
cout << Question.question << endl;
Question.answers[0] = "1. USA";
cout << Question.answers[0] << endl;
Question.answers[1] = "2. India";
cout << Question.answers[1] << endl;
Question.answers[2] = "3. Vatican City";
cout << Question.answers[2] << endl;
cout << endl;
cout << "Choose 1-3: ";
cin >> correct;
if(correct == 3)
cout << "Correct!";
else
cout << "Incorrect!";
cout << endl;
cout << endl;
// Question 2
Quiz2 Question2;
Question2.question2 = "What is the biggest animal in the world?";
cout << Question2.question2 << endl;
Question2.answers2[0] = "1. Elephant";
cout << Question2.answers2[0] << endl;
Question2.answers2[1] = "2. Blue Whale";
cout << Question2.answers2[1] << endl;
Question2.answers2[2] = "3. Great white shark";
cout << Question2.answers2[2] << endl;
cout << endl;
cout << "Choose 1-3: ";
cin >> correct;
if(correct == 2)
cout << "Correct!";
else
cout << "Incorrect!";
return 0;
}
That's as much as non-repetitive as I can imagine after a few minutes of thinking. Maybe it can become smaller, but for my taste this looks alright.
You basically rely on std::vector class, instead of a typical array, because vectors can be of dynamic size. This allows us to use only one struct, but make as many answers as we want (3, 5, 10, whatever). We then create the whole quiz as another vector of questions. We're only left with printing to the console - for that we use loops, as our quiz structure is very simple and self-repetitive.
#include <iostream>
#include <vector>
using namespace std;
struct Question{
string question;
int correct_idx;
vector<string> answers;
Question(string question, int correct_idx, vector<string> answers)
:question(question), correct_idx(correct_idx), answers(answers)
{}
};
int main()
{
vector<Question> whole_quiz = {
Question{
"What is the smallest country?",
2, // indexes start from 0, e.g. 0, 1, 2. So 2 is correct
{"USA", "India", "Vatican City"}
},
Question{
"What is the biggest animal in the world?",
1,
{"Elephant", "Blue Whale", "Great white shark"}
},
};
for(auto question : whole_quiz) {
cout << question.question << endl;
for(int i = 0; i < question.answers.size(); ++i) {
cout << i+1 << ". " << question.answers[i] << endl;
}
cout << "Choose 1-" << question.answers.size() << endl << endl;
int guess;
cin >> guess;
if (guess-1 == question.correct_idx) {
cout << "Correct!" << endl << endl;
} else {
cout << "Incorrect!" << endl << endl;
}
}
return 0;
}
I would propose a more complicated, but also a more fun solution. Have a huge list of answers, like 100, or 1000, or as many as you like. Then in your struct have a std::string question, and std::vector<int> possible answers that are indexes in the huge list. First answer in the list is the correct one. So when you ask a question you pick first index, and three more indexes at random, and you shuffle them up, and present this to the user. The quiz will be different every time.
struct acts as a template, not a single variable. so there's no need to create 2 different struct. Also, a correct variable can be added to the struct for ease of checking.
Code (I split it into different functions for clearer understanding):
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct quiz
{
int correct;
string question;
vector<string> answers;
};
vector<quiz> questionsToAsk;
void addNewQuestion(string ques, vector<string>ans, int cor)
{
quiz q1;
q1.question = ques;
q1.answers = ans;
q1.correct = cor;
questionsToAsk.push_back(q1);
}
void displayQuestion(int idx)
{
quiz cur = questionsToAsk[idx];
cout << cur.question << '\n';
for (int i = 0; i < cur.answers.size(); i++)
{
cout << cur.answers[i] << '\n';
}
cout << "Choose 1-3: "; int inp; cin >> inp;
if (inp == cur.correct) {cout << "Correct";} else {cout << "Incorrect";} cout << '\n';
}
int main()
{
vector<string> ans1({"1. USA", "2. India", "3. Vatican City"});
vector<string> ans2({"1. Elephant", "2. Blue Whale", "3. Great white shark"});
addNewQuestion("What is the smallest county?", ans1, 3);
addNewQuestion("What is the biggest animal in the world?", ans2, 2);
for (int i = 0; i < questionsToAsk.size(); i++)
{
displayQuestion(i);
}
}
Result:
What is the smallest county?
1. USA
2. India
3. Vatican City
Choose 1-3: 1
Incorrect
What is the biggest animal in the world?
1. Elephant
2. Blue Whale
3. Great white shark
Choose 1-3: 2
Correct
You can use a template like
<typename T = int>
T get_answer(std::istream& in) {
T res;
in >> res;
return res;
}
...
if(get_answer(std::cin) == 3)
cout << "Correct!";
else
cout << "Incorrect!";
You can also overload operator<<.
#include <iostream>
#include <string>
template<typename T = int>
T get_answer(std::istream& in) {
T res;
in >> res;
return res;
}
class Quiz{
public:
Quiz(const std::string& q, const std::string& a1, const std::string& a2, const std::string& a3, unsigned correct)
: question(q), answers{a1, a2, a3}{
CheckAnswer(correct);
}
friend std::ostream& operator<<(std::ostream& os, const Quiz& quiz) {
os << quiz.question << "\n";
unsigned i = 1;
for (const auto & answer : quiz.answers) {
os << i++ << ". " << answer << "\n";
}
os << "\n";
return os;
}
void CheckAnswer(unsigned correct) {
std::cout << *this << "Choose 1-3: ";
if(get_answer(std::cin) == correct)
std::cout << "Correct!";
else
std::cout << "Incorrect!";
std::cout << std::endl;
std::cout << std::endl;
}
private:
std::string question;
std::string answers[3];
};
int main()
{
Quiz Question("What is the smallest county?", "USA", "India", "Vatican City", 3);
// Question 2
Quiz Question2("What is the biggest animal in the world?", "Elephant", "Blue Whale", "Great white shark", 2);
return 0;
}
The only thing you can do is define the correct variable in the struct itself. You can use a loop for decreasing the repetitiveness but obviously the question and the answers will have to be stored, it cannot be simplified further.

Accessing multiple instances of a class in C++

I am creating a menu for a restaurant that can have 5 dishes of each category. So far I have created a class for meat dishes and I'm able to add up to 5 dishes, each with a unique identifier. What I am having trouble with is accessing the objects after they have been created.
(There will be multiple categories hence why there is a switch statement with only one case so far).
For example, how would I implement a way to change the description of the second dish?
Here is my code so far:
meat.h
class Meat{
private:
int meatNumber;
std::string meatCategory;
std::string meatDescription[MAX_ITEMS];
double meatPrice[MAX_ITEMS];
public:
Meat();
//setter functions
int setMeatNumber();
std::string setMeatDescription();
double setMeatPrice();
//getter functions
int getMeatNumber();
std::string getMeatCategory();
std::string getMeatDescription(int i);
double getMeatPrice(int i);
};
meat.cpp
#include "Meat.h"
//constructor
Meat::Meat() {
meatNumber = 0;
meatCategory = "Meat";
meatDescription[MAX_ITEMS] = "No description written.";
meatPrice[MAX_ITEMS] = 0.0;
}
//setter functions
int Meat::setMeatNumber(){
static int counter = 1;
meatNumber = counter++;
}
std::string Meat::setMeatDescription(){
int i = 0;
std::cout << "Please enter a short description: " << std::endl;
std::cin >> meatDescription[i];
return meatDescription[i];
}
double Meat::setMeatPrice(){
int i = 0;
std::cout << "Please set the price in a 00.00 format: " << std::endl;
std::cout << "£";
while(!(std::cin >> meatPrice[i])){
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Error. Please enter a number: ";
}
return meatPrice[i];
}
//getter functions
int Meat::getMeatNumber() { return meatNumber; }
std::string Meat::getMeatCategory() { return meatCategory; }
std::string Meat::getMeatDescription(int i) {return meatDescription[i]; }
double Meat::getMeatPrice(int i) { return meatPrice[i]; }
main.cpp
#include <iostream>
#include "Meat.h"
int main() {
int choice;
std::cout << "Menu Creation Terminal\n\n" << std::endl;
std::cout << "\t Welcome\nto Wrapid™ Restaurants\n\n" << std::endl;
std::cout << "1. Add Meat Dish\n2. Add Fish Dish\n3. Add Vegetarian Dish\n4. Add Drink\n"
"5. Edit Current Menu\n6. Quit\n\n" << std::endl;
std::cout << "Please select an option: ";
std::cin >> choice;
switch (choice) {
case 1:
{
int option = true;
int count = 0, i;
Meat meatDish;
std::cout << "Meat Dishes" << std::endl;
while (true) {
meatDish.setMeatNumber();
meatDish.setMeatDescription();
meatDish.setMeatPrice();
//functions to add details to dish
std::cout << "You have added the following dish: " << std::endl;
std::cout << "Item number: \n" << meatDish.getMeatNumber() << std::endl;
std::cout << "Item Category: \n " << meatDish.getMeatCategory() << std::endl;
std::cout << "Item Description: \n" << meatDish.getMeatDescription(i) << std::endl;
std::cout << "Item Price: \n £" << meatDish.getMeatPrice(i) << std::endl;
std::cout << "Would you like to add another item? Press 1 for yes or 2 for no: " << std::endl;
std::cin >> option;
count += 1;
if (count == 5) {
std::cout << "Error. Exceeded maximum items.";
break;
} //breaks out of loop if more than 5 items
if (option == 2) { break; } //breaks out of loop when user is finished adding items
}//while loop to contain menu
}//brace for scope of case 1
}
return 0;
}
As you are using c++ class Meat you can use [] to instantiate N items
for example 5 objects
Meat meats[5];
If you want to modify 2nd object then
meats[1].setMeatDescription(<pass argument>);
You need to change that method using this keyword
this->meatDescription = <pass argument>;
No need to create meatDescription[] as an array
use this code https://pastebin.com/bCkzbFZV you can use meats[i].getMeatDescription()
You could create a new class called DishesContainer. This class could have :
a private std::vector => it will hold every instance
a public function to create a new dish
a public function to change any type of value inside a dish meat.
For exemple to change the description
class DishContainer{
public:
void ChangeDescription(int indexMeat, std::string newDescription){
meats_[indexMeat].setMeatDescription(newDescription);
}
private:
std::vector<Meat> meats_;
}

C++ Player Creation Menu

I am trying to make a text based C++ game.
I have a player class set up and I am now working on a method inside that class called displayMenu(), which will ask the user a variety of questions based on their player and send the data to the main/client code and then that data will create an object of player class via a constructor of player class.
My main question is...
I am trying to compare the input (string) from the user to the (string) they need to inputting, but I am getting an error which says "lower()" can not be resolved. I believe you have to compare each character, but I think there may be a more effective way to code this to provide simplicity and readability. What exactly am I doing wrong? What is the best way to code this?
Here is my code...
void Player::displayMenu(std::string& PlaName, std::string& cName, int& lvl, int& HP)
{
std::cout << "Player Creation Menu" << std::endl;
std::cout << "====================" << std::endl;
std::cout << std::endl;
std::cout << std::endl;
std::cout << "What is your name? " << std::endl;
std::cin >> PlaName;
std::cout << "What is your specitality? " << std::endl;
std::cin >> cName;
while(cName.lower() != "brawler" || cName.lower() != "thief" || cName.lower() != "persuader" || cName.lower()
!= "gunman")
{
std::cout << "That is not your true specitality..." << std::endl;
std::cout << "You must pick from { 'Brawler', 'Thief' , 'Persuader', 'Gunman' }" << std::endl;
std::cin >> cName;
}
}
I have several remarks on your original code:
Reading and comparing the strings seems like a bit complicated for this use-case. It is common to see usage of first character as identifier, to make it simpler.
The specialty is a classic example for enum (or enum class, which is enum that you must use always with it's name)
The displayMenu method should not be part of the Player class, since it isn't a behavior (an action) of the player. It should be part of the "Game"/"UI" class.
If you really want to use the complete string in order to identify the specialty, you can use the code examples in the first answer in the link Ayxan put in the comments.
Here is my proposed code:
#include <iostream>
constexpr char INVALID_CHARACTER_INPUT = '#';
enum class CharacterSpecialty
{
BRAWLER,
THIEF,
PERSUADER,
GUNMAN,
NUM_OF_SPECIALITY_TYPES
};
`
class Player
{
public:
Player(const std::string& player_name, CharacterSpecialty char_specialty) :
name(player_name),
specialty(char_specialty)
{
}
private:
std::string name;
CharacterSpecialty specialty;
};
Player displayMenuAndCreatePlayer()
{
std::cout << "\nPlayer Creation Menu\n" << "====================\n\n" << std::endl;
std::cout << "Enter your name: " << std::endl;
std::string player_name{};
std::cin >> player_name;
CharacterSpecialty char_specialty = CharacterSpecialty::NUM_OF_SPECIALITY_TYPES;
while(char_specialty == CharacterSpecialty::NUM_OF_SPECIALITY_TYPES)
{
std::cout << "What is your specialty?\n" << "[B]rawler, [T]hief, [P]ersuader or [G]unman"<< std::endl;
std::string char_type_input;
std::cin >> char_type_input;
char input = char_type_input.size() == 1 ? char_type_input[0] : INVALID_CHARACTER_INPUT;
switch(char_type_input)
{
case 'b':
case 'B':
char_specialty = CharacterSpecialty::BRAWLER;
break;
case 't':
case 'T':
char_specialty = CharacterSpecialty::THIEF;
break;
case 'p':
case 'P':
char_specialty = CharacterSpecialty::PERSUADER;
break;
case 'g':
case 'G':
char_specialty = CharacterSpecialty::GUNMAN;
break;
default:
std::cout << "Invalid Specialty Entered!\n" << std::endl;
break;
}
}
return Player(player_name, char_specialty);
}
int main()
{
Player player = displayMenuAndCreatePlayer();
}

vector<string> in a struct doesn't work properly

I declared a vector<string> and I cannot even compile it. I tried many ways but none of them worked.
I'm trying to write out the x.surname.push_back(word)[i] but it's definetly written wrongly and I have no idea how to write it properly and make it possible to compile.
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int number, i = 0;
string word;
struct donators {
vector<string> surname;
vector<int> amount;
} x;
cout << "How many donators do you want to register? " << endl;
cin >> number;
for (i = 0; i < number; i++) {
cout << "Surname: ";
cin >> word;
x.surname.push_back(word)[i];
cout << "Amount: ";
x.amount.push_back(i);
cin >> x.amount[i];
}
cout << "OUR GORGEUS DONATORS: " << endl;
for (i = 0; i < number; i++) {
if (x.amount[i] >= 10000) {
cout << "Surname: " << x.surname(word)[i];
cout << "Amount: " << x.amount[i] << endl;
}
else if (x.amount[i] < 10000) {
cout << "Lack of surnames!" << endl;
}
}
cout << "OUR CASUAL DONATORS: " << endl;
for (i = 0; i < number; i++) {
if (x.amount[i] < 10000) {
cout << "Surname: " << x.surname(word)[i];
cout << "Amount: " << x.amount[i] << endl;
} else if (x.amount[i] >= 10000) {
cout << "Lack of surnames!" << endl;
}
}
return 0;
}
And one more thing. How to make sentence "Lack of surnames!" to be written out once? In some cases, it is written out twice or more times what is redundant.
You are putting [i] at seemingly random places in your code. Such as in x.surname.push_back(word)[i];. Don't add things like this to your code if you're unsure about what they're doing.
The x.surname(word)[i] construct are also wrong. What's x.surname(word) supposed to be? This syntax is for function calls. surname, however, is not a function. It's a std::vector<std::string>. Just put x.surname[i] instead.
And one more thing. How to make sentence "Lack of surnames!" to be
written out once? In some cases, it is written out twice or more times
what is redundant.
That's because you write it for every donor that doesn't fit the criterion. Instead, keep track if any donor fits the criterion and only print it when none ends up fitting. You can do it like this:
bool HasGorgeousDonators = false;
And then in the loop:
if (x.amount[i] >= 10000)
{
cout << "Surname: " << x.surname[i];
cout << "Amount: " << x.amount[i] << endl;
HasGorgeousDonators = true;
}
And after the loop:
if (!HasGorgeousDonators)
cout << "Lack of surnames!" << endl;
Likewise for the other loop. Also, please consider the following Q&A:
Why is "using namespace std;" considered bad practice?
It seems like you are writing C with some C++ help functions. However C++ is a different language. Sure, it supports some C structures, but there's so much more.
Take a look at some of my suggestions for implementation and compare it to your code:
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
template<typename T>
T ReadCin(std::string_view const& sv = "") {
T retVal;
if (!sv.empty()) std::cout << sv;
std::cin >> retVal;
return retVal;
}
class Donator {
private:
std::string surname{};
int amount{};
public:
constexpr bool IsGenerous() const noexcept { return amount >= 10000; }
void Read() noexcept {
surname = ReadCin<decltype(surname)>("Surname: ");
amount = ReadCin<decltype(amount)>("Amount: ");
}
friend std::ostream& operator<<(std::ostream& out, Donator const& donator) noexcept {
out << "Surname: " << donator.surname << ", " << "Amount: " << donator.amount;
return out;
}
};
int main() {
std::vector<Donator> donators(ReadCin<int>("How many donators do you want to register?\n"));
for (auto& donator : donators) donator.Read();
std::cout << "OUR GENEROUS DONATORS:\n";
std::copy_if(std::cbegin(donators), std::cend(donators), std::ostream_iterator<Donator>(std::cout, "\n"),
[](Donator const& donator) { return donator.IsGenerous(); });
std::cout << "OUR CASUAL DONATORS:\n";
for (auto const& donator : donators) if (!donator.IsGenerous()) std::cout << donator << '\n'; //alternative
}
I tried to include some of the possibilities using C++. I would really advise you to get a good book on C++.

c++ function redefining (code not working - logic error)

I am currently learning c++ and i am now working on Inheritance.
I have to make a regular question class as well as a derived class that is a Numeric question and a multiple choice question. I make the questions in the code, and then display them 1 by 1 to the user. The user then answers the questions, and the program is supposed to check whether the answer is correct.
#include <iostream>
#include <string>
using namespace std;
class Question {
protected:
string text;
string answer;
string input;
public:
Question(string inText, string inAnswer) {
text = inText;
answer = inAnswer;
}
Question() {
text = "blank question";
answer = " ";
}
void setQuestion(string txt) {
text = txt;
}
void setAnswer(string answr){
answer = answr;
}
void userAnswer(string ans) {
input = ans;
}
string getAnswer() {
return answer;
}
string getQuestion() {
return text;
}
void displayQuestion() {
cout << getQuestion() << endl;
}
void isCorrect() {
cout << "default function" << endl;
if (input.compare(answer) == 0)
cout << "True" << endl;
else
cout << "False" << endl;
}
};
class NumericQuestion : public Question {
protected:
double ans;
double inp;
public:
NumericQuestion(string inText, double inAns) {
text = inText;
ans = inAns;
}
void userAnswer(string ans) {
inp = stod(ans);
}
void isCorrect() {
cout << "numeric function" << endl;
if (inp == ans)
cout << "True" << endl;
else if ((inp - ans) <= 0.01)
cout << "False" << endl;
else
cout << "False" << endl;
}
};
class MultipleChoice : public Question {
protected:
string qA, qB, qC, qD;
public:
MultipleChoice(string inText, string qA, string aB, string qC, string qD, char inAnswer) {
text = inText;
answer = inAnswer;
}
void displayQuestion() {
cout << text << endl;
cout << "a) " << qA << " " << "b) " << qB << endl;
cout << "c) " << qC << " " << "d) " << qD << endl;
}
};
int main() {
string ans;
Question q1("whats 2+2", "four");
NumericQuestion q2("2+2", 4);
MultipleChoice q3("The Right Answer is C", "answer A", "thisisB", "thats C", "Wrong", 'c');
Question arr[] = { q1,q2,q3};
for (int i = 0; i < 3; i++) {
arr[i].displayQuestion();
cin >> ans;
arr[i].userAnswer(ans);
arr[i].isCorrect();
}
getchar();
return 0;
}
The member function isCorrect() from NumericQuestion class and displayQuestion() from MultipleChoice class don't get used, instead, the ones from Question class get used, which lead to logical errors in my code.
You're slicing objects when you assign subclasses of Questions by value to an array of Question when you do Question arr[] = { q1, q2, q3 };. This means that even though some of your derived Question objects have extra members that the base class doesn't, they're being truncated away by the assignment into the array. Another problem is that because arr is declared to hold plain and simple Question objects, the compiler will assume that a call like arr[i].isCorrect(); will always refer to Question::isCorrect(), and not a derived method. Here's a couple things to fix.
Make overridable functions virtual:
class Question {
...
virtual void isCorrect() {
cout << "default function" << endl;
if (input.compare(answer) == 0)
cout << "True" << endl;
else
cout << "False" << endl;
}
and override them in subclasses:
class NumericQuestion : public Question {
...
void isCorrect() override {
cout << "numeric function" << endl;
if (inp == ans)
cout << "True" << endl;
else if ((inp - ans) <= 0.01)
cout << "False" << endl;
else
cout << "False" << endl;
}
Finally, avoid the slicing by storing base class pointers to your Questions. Here, I'm using std::shared_ptr to avoid the headaches of manual memory management. Also appearing is a ranged-for loop:
auto q1 = std::make_shared<Question>("whats 2+2", "four");
auto q2 = std::make_shared<NumericQuestion> q2("2+2", 4);
auto q3 = std::make_shared<MultipleChoice>("The Right Answer is C", "answer A", "thisisB", "thats C", "Wrong", 'c');
// even though q1...q3 are shared_ptrs to derived classes, they can be safely cast to shared_ptrs to the base class
std::vector<std::shared_ptr<Question>> questions { q1, q2, q3 };
for (const auto& question: questions) {
question->displayQuestion();
cin >> ans;
question->userAnswer(ans);
question->isCorrect();
}
You need to set userAnswer, displayQuestion and isCorrect as virtual in the base class.
You also need to store your question as pointers (there's other options) to prevent slicing. Personally, I find it simpler to fix it like this:
Question* arr[] = {&q1,&q2,&q3};
...
arr[i]->displayQuestion();
(you need to change all usage or arr[i] to use arrows)
There are two issues at play here.
1) Based on your for loop at the end, you need to declare some functions, like displayQuestion(), userAnswer(), and isCorrect() as virtual.
2) Secondly, change your arr declaration to Question *arr[] = {&q1, &q2, &q3};.