c++ instantiate several classes if a condition is true - c++

Is there a way I can make this work?
I want to create 5 instances of bank if age is greater than 17, but I am getting this error:
[Error] no matching function for call to 'Bank::Bank()'
I need to get this right for my assignment in school.
#include <iostream>
#include <string>
using namespace std;
class Bank{
string Fullname;
string StateOfOrigin;
int Age;
public:
Bank(string name, string state, int age){
Fullname = name;
StateOfOrigin = state;
Age = age;
}
string getname(){
return Fullname;
}
string getstate(){
return StateOfOrigin;
}
int getage(){
return Age;
}
};
int main(){
Bank customer[20];
int x,y,z,age;
string name;
string state;
cout<<"==============================="<<endl;
cout<<"Welcome To Hojma Bank.Plc"<<endl;
cout<<"How many accounts do you want to create? \n";
cin>>y;
for(int k = 0; k < y; k++){
cout<<"Please input your fullname"<<endl;
cin>>name;
cout<<"Please input your state of origin"<<endl;
cin>>state;
cout<<"Please input your age";cout<<endl;
cin>>age;
if(age >= 18){
Bank customer[y](name,state,age);
cout << customer[y].getname();
}
}
}

Bank customer[20];
Here you default-construct twenty Bank objects (oddly called customer??). Or, at least, you tried to, but your Bank class has no default constructor. Neither should it, from what I can tell.
Bank customer[y](name,state,age);
cout << customer[y].getname();
Here I guess you tried to "declare" individual array elements, but it doesn't work like that.
Also your usage of y is wrong; you can accept y maximum, but you probably meant to use the current loop counter value, k. That's broken too because you have a filter on age so you might skip some array elements.
Why not use a nice tasty std::vector, and add new customers at will? Then you can also get rid of those confusing ints, half of which you're not even using.
int main()
{
int y = 0;
cout << "===============================\n";
cout << "Welcome To Hojma Bank.Plc\n";
cout << "How many accounts do you want to create?" << endl;
cin >> y;
std::vector<Bank> customers;
for (int i = 0; i < y; i++) {
int age;
string name;
string state;
cout << "Please input your full name" << endl;
cin >> name;
cout << "Please input your state of origin" << endl;
cin >> state;
cout << "Please input your age" << endl;
cin >> age;
if (age >= 18){
customers.emplace_back(name,state,age);
cout << customer.back().getname();
}
}
}
You could do with some error checking on your user input, too. And rename that class to Customer.

If you create an array of objects (Bank customer[20]), the class needs to have a default constructor. Just define something like this:
Bank() : Fullname(""), StateOfOrigin(""), Age(0) {}

Related

Exception has occured, unknown signal error when using class object again inside each function

I'm trying to write a C++ code for a course I'm enrolled in, where I keep the information of the students enrolled in the course.
I should be able to add a student to the classrrom in the user interface written in main , by calling the function void addNewStudent(int ID, string name, string surname), where I create my object instances, Student, and Course inside the function.
I should also be able to search by given ID by calling the function void showStudent(int ID) in the main, where the function uses the getStudent(ID) method of the object of the classCourse
I did not write all the methods, but when I try to debug this code, I got the error " Exception has occured, unknown signal error."
My questions are:
What is the reason of this error? How can I fix it?
Suppose that the user interface in the main is necessary to use as well as the functions it calls. Do I have to create a class object again inside each function as I wrote?
Can a more effective implementation be made in accordance with the object oriented principles I have defined above?
#include <iostream>
using namespace std;
#define MAX 10
class Student {
private:
int ID;
string name;
string surname;
public:
Student()
{
ID = 0;
string name = "" ;
string surname = "";
}
void setID(int ID_set);
int getID();
void setName(string name_set);
string getName();
void setSurName(string surname_set);
string getSurName();
};
class Course {
private:
Student students[MAX];
int num =0 ; // The current number of students in the course, initially 0.
float weightQ;
float weightHW;
float weightF;
public:
Course()
{
students[num] = {};
weightQ = 0.3;
weightHW = 0.3;
weightF = 0.4;
}
int getNum(); // Returns how many students are in the course
void addNewStudent(Student new_student);
void updateWeights(float weightQ_update, float weightHW_update, float weightF_update);
void getStudent(int ID_given);
};
// Method declerations for the class Student
void Student :: setID(int ID_set){
ID = ID_set;
}
int Student :: getID(){
return ID;
}
void Student :: setName(string name_set){
name = name_set;
}
string Student :: getName(){
return name;
}
void Student :: setSurName(string surname_set){
surname = surname_set;
}
string Student :: getSurName(){
return surname;
}
// Method declerations for the class Course
int Course :: getNum(){
return num;
}
void Course :: addNewStudent(Student new_student){
students[num] = new_student ;
num = num + 1;
}
void Course :: updateWeights(float weightQ_update, float weightHW_update, float weightF_update){
weightQ = weightQ_update;
weightHW = weightHW_update;
weightF = weightF_update;
}
void Course :: getStudent(int ID_given){
for(int i = 0; i<MAX; i++){
if(ID_given == students[i].getID()){
cout << "Student Name & Surname : " << students[i].getName() << " " << students[i].getSurName()<<"\n";
}
}
}
void addNewStudent(int ID, string name, string surname){
Student student;
Course ECE101;
student.setID(ID);
student.setName(name);
student.setSurName(surname);
ECE101.addNewStudent(student);
}
void showStudent(int ID){
Course ECE101;
ECE101.getStudent(ID);
}
int main(){
Course ECE101;
cout << "Welcome to the ECE101 Classroom Interface"<<"\n";
cout << "Choose your option\n";
string option_1 = "1) Add a student ";
string option_2 = "2) Search a student by ID";
cout << "Enter your option: ";
int x;
int ID;
string name, surname;
cin >> x;
if (x == 1)
cout << "Enter the student ID ";
cin >> ID;
cout << endl;
cout << "Enter the student name ";
cin >> name;
cout << endl;
cout << "Enter the student surname " ;
cin >> surname;
addNewStudent(ID, name, surname);
return 0;
}
 To make the menu more interactive you could add a do while statement that would accept 3 options:
register
show data
exit
int main(){
Course ECE101;
int x;
int ID;
string name, surname;
string option_1 = "1) Add a student\n";
string option_2 = "2) Search a student by ID\n";
cout << "Welcome to the ECE101 Classroom Interface\n";
cout << "Choose your option\n";
cout << option_1 << option_2;
cin >> x;
do {
if (x == 1) {
cout << "Enter the student ID ";
cin >> ID;
cout << endl;
cout << "Enter the student name ";
cin >> name;
cout << endl;
cout << "Enter the student surname " ;
cin >> surname;
addNewStudent(ID, name, surname, ECE101);
}
else {
cout << "Enter the student ID\n";
cin >> ID;
showStudent(ID, ECE101);
}
cout << "Choose your option\n";
cin >> x;
} while(x != 3);
return 0;
}
addnewStudent() and showStudent() methods now accepts an instance of Course as an argument to be able to add students.
void addNewStudent(int ID, string name, string surname, Course &course) {
Student student;
student.setID(ID);
student.setName(name);
student.setSurName(surname);
course.addNewStudent(student);
}
void showStudent(int ID, Course &course) {
course.getStudent(ID, course);
}
the function is modified from the same class as well.
void Course::getStudent(int ID_given, Course &course) {
for(int i = 0; i<MAX; i++){
if(ID_given == students[i].getID()){
cout << "Student Name & Surname : " << students[i].getName() << " " << students[i].getSurName()<<"\n";
}
}
}
Demo
Your addNewStudent function creates a new course everytime it is called. You could pass a reference to the course as a parameter into the function and call Course.addNewStudent(student). You'll want to make sure you specify it's a reference though when you define your function or you'll just create a copy of the course.

how can I print dynamic array in c++ I need explanation to this question

This is the question my teacher gave me:
Construct a structure Employee that consists of the following fields:
ID, name, degree, age
A function that creates an object (a variable of Employee type), fills it from the user the, then returns it.
A function that receives an object (a variable of Employee type) and prints its fields.
Inside the main function:
Ask the user to specify the number of employees.
Create a dynamic array of the size specified by the user for the employees.
Inside a loop, fill the array elements one at a time by calling the first function.
Inside another loop, print the array elements one at a time by calling the second function.
I tried to solve it although I didn't understand it and this is what I have, Pleas help:
struct Employee
{
int ID;
char name[10];
char degree;
int age;
};
int fillin()
{ Employee employee;
cout<<"Enter employee ID, NAME, DEGREE and AGE:\n";
cin>>employee.ID;
cin>>employee.name;
cin>>employee.degree;
cin>>employee.age;
}
int print()
{
Employee employee;
cout<<"ID: "<< employee.ID<<" , ";
cout<<"NAME: "<< employee.name<<" , ";
cout<<"Degree: "<< employee.degree<<" , ";
cout<<"AGE: "<< employee.age<<".\n ";
}
int main()
{
int num;
cout<<"Enter number of employees: ";
cin>> num;
string *name= new string[num];
for(int i = 0; i < num;i++)
{
name[i]=fillin();
}
for(int j : name){
print();
}
return 0;
}
A function can have parameters and return a value. So here, fillin should return an Employee object, and print should take an Employee (or better a const reference) parameter:
Employee fillin()
{ Employee employee;
cout<<"Enter employee ID, NAME, DEGREE and AGE:\n";
cin>>employee.ID;
cin>>employee.name;
cin>>employee.degree;
cin>>employee.age;
return employee; // return the local object
}
void print(const Employee& employee)
{
cout<<"ID: "<< employee.ID<<" , ";
cout<<"NAME: "<< employee.name<<" , ";
cout<<"Degree: "<< employee.degree<<" , ";
cout<<"AGE: "<< employee.age<<".\n ";
}
Your main function could become:
int main()
{
int num;
cout<<"Enter number of employees: ";
cin>> num;
Employee *name= new Employee[num];
for(int i = 0; i < num;i++)
{
name[i]=fillin();
}
for(int i=0; i<num; i++){
print(name[i]);
}
return 0;
}
Of course, you should check that the input methods return valid values (check cin after each read)
There are several issues with the code, below is the working example.
the functions should receive and return parameters somehow, references are used in the code
array should be of appropriate type
wrong iterator used
However, keep in mind that there are more issues with the code, like no boundary checking, it is better to use STL library... consider this just as a starting point.
#include <iostream>
using namespace std;
struct Employee
{
int ID;
char name[10];
char degree;
int age;
};
int fillin(Employee& employee)
{
cout<<"Enter employee ID, NAME, DEGREE and AGE:\n";
cin>>employee.ID;
cin>>employee.name;
cin>>employee.degree;
cin>>employee.age;
}
int print(const Employee& employee)
{
cout<<"ID: "<< employee.ID<<" , ";
cout<<"NAME: "<< employee.name<<" , ";
cout<<"Degree: "<< employee.degree<<" , ";
cout<<"AGE: "<< employee.age<<".\n ";
}
int main()
{
int num;
cout<<"Enter number of employees: ";
cin>> num;
Employee *emp= new Employee[num];
for(int i = 0; i < num;i++)
{
fillin(emp[i]);
}
for(int j = 0; j< num; j++){
print(emp[j]);
}
return 0;
}
Employee fillin()
{
Employee employee;
cout << "Enter employee ID, NAME, DEGREE and AGE:\n";
cin >> employee.ID;
cin >> employee.name;
cin >> employee.degree;
cin >> employee.age;
return employee;
}
void print(Employee emp)
{
cout << "ID: " << emp.ID << " , ";
cout << "NAME: " << emp.name << " , ";
cout << "Degree: " << emp.degree << " , ";
cout << "AGE: " << emp.age << ".\n ";
}
This should help put you on the right track. You just need the dynamic array to accept Employee objects and then you need to supply the objects to print when you call print(someEmployeeObject) in main.
Okay, I have a variety of comments on your code. First, do not use character arrays. Use string instead:
#include <string>
struct Employee
{
int ID;
std::string name;
char degree;
int age;
};
String allows for dynamic-length strings, so if someone enters a really, really long name, you won't overrun the space. It will just handle it. Plus there are a bunch of other advantages.
Next, let's change this method just slightly:
Employee fillin() {
Employee employee;
cout<<"Enter employee ID, NAME, DEGREE and AGE:\n";
cin>>employee.ID;
cin>>employee.name;
cin>>employee.degree;
cin>>employee.age;
return employee;
}
You weren't returning anything at all, but you need to return the employee you're creating. So this is a small change.
And now a small change to the print method:
#include <iostream>
std::ostream & operator<<(std::ostream &ostr, const Employee &employee) {
{
ostr <<"ID: "<< employee.ID<<" , ";
ostr <<"NAME: "<< employee.name<<" , ";
ostr <<"Degree: "<< employee.degree<<" , ";
ostr <<"AGE: "<< employee.age<<".\n ";
return ostr;
}
Then to use it:
std::cout << employee;
This is the C++ way to do it and lets you use the exact same method if you want to dump the employee somewhere else (like a file).
And finally, small changes to your main:
#include
int main()
{
std::vector employees;
int num;
cout<<"Enter number of employees: ";
cin>> num;
for(int i = 0; i < num;i++)
{
employees.push_back(fillin());
}
for (const Employee &employee: employees) {
std::cout << employee;
}
return 0;
}
Let's talk about this. First, rather than using a fixed-length array, we're using a vector. This is a dynamic-length array similar to how string is a dynamic length string. You can push_back() to append items to the array. When defining it, you specify what it holds. So in this case, I have a vector of Employee objects.
I started with your for-loop, but I call the new version of fillin to actually get an employee record, and then I push them into the vector.
Then there's a second for-loop. You may not be familiar with this style. Basically that's a for-loop that iterates over every element of employees -- the ones we just did push_back() on. And then I use the output method I wrote earlier.
You were close. You were just missing a few key things -- basically passing elements into your methods and returning elements.

To find max salary using friend function of a class having employee details(name,ID, position,salary) and print max salary details

#include <iostream.h>
#include <conio.h>
class Employee{
int Id;
string Name;
string Post;
public:
long int Salary;
void GetDetails();
void DisplayDetails();
friend void MaxSalary();
};
void Employee::GetDetails(){
cout << "\nEnter Employee Id : ";
cin >> Id;
cout << "\nEnter Employee Name : ";
cin.ignore();
getline(cin,Name);
cout << "\nEnter Employee Post : ";
cin.ignore();
getline(cin,Post);
cout << "\nEnter Employee Salary : ";
cin >> Salary;
}
void Employee::DisplayDetails(){
cout << "\nEmployee Id : " << Id;
cout << "\nEmployee Name : " << Name;
cout << "\nEmployee Post : " << Post;
cout << "\nEmployee Salary : " << Salary;
}
void MaxSalary(Employee a[], int x){
long int max;
for(int j=0; j<x; j++){
if(a[j].Salary>a[j+1].Salary)
max=a[j].Salary;
}
cout<<"Maximum Salary = "<<max<<endl;
}
int main()
{
int n, i;
cout<<"Enter Number of Employees : ";
cin>>n;
Employee E[n];
cout<<"\n\n----------ENTER DETAILS OF EMPLOYEES----------\n\n";
for(i=0;i<n;i++){
cout<<"\n\n Enter details of Employee "<<i+1<<endl;
E[i].GetDetails();
}
cout<<"\n\n----------DETAILS OF EMPLOYEES----------\n\n";
for(i=0;i<n;i++){
cout<<"\n\n Details of Employee "<<i+1<<endl;
E[i].DisplayDetails();
}
MaxSalary(E[n], n );
return 0;
}
There are lots of defects in the given code:
The variable length arrays (VLAs) are not allowed in C++. In other words, the syntax:
cin >> x;
Employee emp[x];
is invalid. Note that C99 is an exception in this case.
In the For loop of MaxSalary(), a[j + 1] is given, it will access out-of-bounds array, which invokes an undefined behavior.
Declaring a variable in a class as public breaks the rule of OOP:
public:
long int Salary; // Not a good idea
You do not need to pass [n] as the function argument:
MaxSalary(E[n], n);
The refined code would look like:
#include <iostream>
#include <limits>
#include <vector>
// Using this statement in order to reduce the spam of 'std::' here
using namespace std;
class Employee {
int ID;
string name;
string post;
long int salary;
public:
Employee() {}
// Initializing the class object
void initEmployee(int id, string varName, string varPost, long sal) {
ID = id, \
name = varName, \
post = varPost, \
salary = sal;
}
// 'salary' getter
long getSalary() {
return salary;
}
// The friend function
friend void maxSalary(vector<Employee> data) {
int max = 0;
for (size_t i{1}, len = data.size(); i < len; i++)
// Comparison
if (data[i].getSalary() > data[i - 1].getSalary())
max = data[i].getSalary();
// After the loop execution, prints the maximum salary
std::cout << "Maximum salary: " << max << endl;
}
};
int main(void) {
int total;
cout << "Enter the total number of employees: ";
cin >> total;
vector<Employee> emp(total);
for (int i{}; i < total; i++) {
// Temporary variables to store data in each iteration
Employee temp;
string tempName;
string tempPost;
int tempID;
long int tempSal;
cout << "Name of the employee " << i + 1 << ": ";
getline(cin, tempName);
// Clearing the 'cin' in order to prevent the getline skips
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Post of the employee: ";
getline(cin, tempPost);
cout << "Employee ID: ";
cin >> tempID;
cout << "Total salary: ";
cin >> tempSal;
// Initializing the temporary object
temp.initEmployee(tempID, tempName, tempPost, tempSal);
// Pushing the object into the main vector
emp.push_back(temp);
}
// Comparing the vector elements (note: it is a friend function)
maxSalary(emp);
return 0;
}
As a test case:
Enter the total number of employees: 2 // Number of employees
Name of the employee 1: John Doe // Employee 1
Post of the employee: Manager
Employee ID: 100
Total salary: 15000
Name of the employee 2: Max Ville // Employee 2
Post of the employee: Assitant Manager
Employee ID: 102
Total salary: 50000
Maximum salary: 50000 // Maximum salary

How can I find in an array of objects the main actor I need

This is my task:
I have done half of my code, but I'm struggling because I'm a beginner in OOP and I'm not sure how I can find movie where main_actor is Angelina Jolie.
for (int i = 0; i < n; ++i)
{
string name;
int year;
string prod;
string actor;
cout << "\nenter the film name " ;
cin >> name;
cout << "\nenter the production year ";
cin >> year;
cout << "\nenter the producer name ";
cin >> prod;
cout << "\nenter the actor name ";
cin >> actor;
obs[i].SetName(name);
obs[i].SetYearP(year);
obs[i].SetProducer(prod);
obs[i].SetMaina(actor);
if (actor == "Angelina Jolie")
{
cout << "The movie who has main actor Angelina Jolie is" << name << endl;
} // Тhis is my attempt.
}
}
You need to make a function that loops over your array and checks the main-actor:
bool findFilm(Film* films, int numFilms, string actor)
{
bool found = false;
for (int i = 0; i< numFilms; i++) {
if(!actor.compare(0, films[i].GetyMaina().length(), films[i].GetyMaina()){
cout<<"Film "<<films[i].GetName()<<" has main actor "<<actor<<"\n";
found = true;
}
}
return found;
}
The first thing you should do is using C++ containers like std::vector, std::array instead of raw array. And of course, then you should fill them.
std::vector<Films> films;
std::array<Films, 100> films;
The seconds thing is, you should delete "Films() = default;" part. That declaration changes everything in C++.
After these changes, you will be able to use containers' template member functions and algorithm functions (like find(), find_if(), count() etc.) to get what you need.
#include <algorithm>
If you are not able to do these changes, simply you can do it by looping:
for(auto film : films){
//comparisons, if checks, returns
}
Please use getline() function for user input because cin >> name will save from name Angelina Jolie only Angelina. Because it is reading only whole words not including white space.
To use function getline() put this after #include<cstring>
#include <string>
So use getline like this :
cout << "\n enter the actor name ";
std::getline (std::cin,actor);
Another problem is that you need cin.ignore() between two inputs. Because you need to flush the newline character out of the buffer in between.
Before loop ask for data like this :
cout << "how many films ";
cin >> n;
cin.ignore();
In loop like this :
cout << "\n enter the film name ";
getline(cin, name);
cout << "\n enter the production year ";
cin.ignore();
cin >> year;
cout << "\n enter the producer name ";
cin.ignore();
getline(cin, prod);
cout << "\n enter the actor name ";
getline(cin, actor);
b) (put this function in your class in public section right after string GetMania() ):
static void FindFilm(Film arr[], int cntFilms, string actor)
{
for (int i = 0; i < cntFilms; i++)
{
if (arr[i].GetMaina() == "Angelina Jolie")
cout << "The movie who has main actor Angelina Jolie is" << arr[i].GetName() << endl;
}
}
And from main call it like this right after loop.
string actor = "Angelina Jolie";
Film::FindFilm(obs, n, actor);
Also it's better if you write escape sequence (or special character) for new line (\n) to the end of output message. Like this :
cout << "The name of movie: \n" << name;

C++ Classes, Basic overloading errors

I am trying to make a program that makes a class called student that as a student ID, an array of grades, and a number showing how many grades are in the array. The class is supposed to have member methods that enter a student ID number, enter a single test grade and update the total number of grades entered, and compute an average grade and display the student ID followed by the average grade. Here is my code so far.
#include <iostream>
using namespace std;
class Student
{
public:
int StudentID;
double Grades[5];
int NumberOfGrades;
// Member functions declared here
int setID(int id);
double setGrades(double g[5]);
double getAverage(void);
};
// make them functions work, son.
int Student::setID(int ID)
{
cout << "Please enter in the student's ID number: ";
cin >> ID;
return 0;
}
double Student::setGrades(double g[5])
{
for (int i = 0; i < 5; i++)
{
cout << "Please enter in grade number " << i ;
cin >> g[i];
NumberOfGrades++;
}
return 0;
}
double Student::getAverage(void)
{
int sum = 0,average; // declare what I need in average
for (int i = 0; i < 5; i++)
{
sum = sum + Grades[i];
}
average = sum / NumberOfGrades;
cout << "The average for " << StudentID << " is " << average;
return 0;
}
int main ()
{
Student Student1;
Student1.setID; // error
Student1.setGrades; // error
Student1.getAverage();
}
I am getting the error saying that it cannot resolve the address of overloaded function. Can someone explain to me what an overloaded fuction is, in simplest terms possible? Also, if possible, could anyone explain why I got that error in my code?
First of all, you need to actually call these functions:
Student1.setID -> Student1.setID()
Student1.setGrades -> Student1.setGrades()
That's not enough, though, these function require arguments (int and double[5], respectively). So:
int id = 65;
double grades[5] = { 3.5, 4.0, 4.0, 3.0, 4.5 };
Student1.setID(id);
Student1.setGrades(grades);
This will only remove compiler errors, though. Perhaps you don't see this, but your functions are implemented incorrectly:
int Student::setID(int ID)
{
cout << "Please enter in the student's ID number: ";
cin >> ID; //you fill ID, which is a temporary variable!
return 0;
}
Also, if you ask user inside setID() for id, what is the purpose of this parameter? Remove it - change setID(int ID) to setID():
int Student::setID()
{
int input_id;
cout << "Please enter in the student's ID number: ";
cin >> input_id;
this->StudentID = input_id;
return 0;
}
I see a few major problems with the code:
int Student::setID(int ID)
{
cout << "Please enter in the student's ID number: ";
//ID is local. Assigning any value to it will have no effect on the class
cin >> ID;
//You might as well not return anything if the function is purely impure
return 0;
}
The other issue is a "setter" shouldn't be taking input from a user, and doing an assignment; those are 2 separate tasks. I'd set up this function as:
void Student::setID(int ID)
{
StudentID = ID;
}
Notice that we're assigning to the StudentID a value passed in as an argument. Use like:
//In main
Student student;
int newStudentID = 1234;
student.setID(newStudentID);