Cout not printing out expected results - c++

When I compile the below code, for some reason, the student/instructors name, age, and GPA/Rating, are not returned via their respective printPerson functions.
With the name variable, nothing is printed to the console.
With the age, GPA/Rating, console prints out a negative 8 digit number, and a negative float.
What am I not seeing?
Person.h
#pragma once
#ifndef PERSON_H
#define PERSON_H
#include <iostream>
#include <vector>
#include <string>
using std::string;
// Base class
class Person {
protected:
string name;
int age;
public:
void setName(string name);
void setAge(int age);
virtual void do_work(int number) {};
virtual void printPerson() {};
};
#endif;
Person.cpp
#include "Person.h"
#include <iostream>
#include <vector>
#include <string>
using std::cout;
using std::cin;
using std::endl;
void Person::setName(string name) {
name = name;
}
void Person::setAge(int age) {
age = age;
}
Student.h
#pragma once
#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
#include <vector>
#include <string>
#include "Person.h"
using std::string;
class Student : public Person {
private:
float gpa;
public:
void setGPA(float gpa);
float getGPA();
void do_work(int number);
void printPerson();
};
#endif;
Student.cpp
#include "Student.h"
#include <iostream>
#include <vector>
#include <string>
using std::string;
using std::cout;
using std::cin;
using std::endl;
void Student::setGPA(float gpa) {
gpa = gpa;
}
float Student::getGPA() {
return gpa;
}
void Student::do_work(int number) {
//cout << name << ".. " << number << "hours of homework.” << endl;
cout << name;
}
void Student::printPerson() {
cout << "Name : " << name << "Age :" << age << " GPA : " << getGPA() << endl;
}
Instructor.h
#pragma once
#ifndef INSTRUCTOR_H
#define INSTRUCTOR_H
#include <iostream>
#include <vector>
#include <string>
#include "Person.h"
class Instructor : public Person {
private:
float rating;
public:
void setRating(float rating);
float getRating();
void do_work(int number);
void printPerson();
};
#endif;
Instructor.cpp
#include "Instructor.h"
#include <iostream>
#include <vector>
#include <string>
using std::string;
using std::cout;
using std::cin;
using std::endl;
void Instructor::setRating(float rating) {
rating = rating;
}
float Instructor::getRating() {
return rating;
}
void Instructor::do_work(int number) {
cout << name << "graded papers for" << number << "hours." << endl;
}
void Instructor::printPerson() {
cout << " Name : " << name << " Age : " << age << " Rating : " << getRating() << endl;
}
University.h
#pragma once
#ifndef UNIVERSITY_H
#define UNIVERSITY_H
#include <iostream>
#include <vector>
#include <string>
#include "Person.h"
#include "Building.h"
#include "Student.h"
using std::cout;
using std::string;
using std::vector;
class University {
public:
string name;
vector<Person*> persons;
vector<Building> buildings;
public:
void printAllBuildings();
void printAllPersonsRecord();
};
#endif;
University.cpp
#include "University.h"
#include <iostream>
#include <vector>
#include <string>
using std::string;
using std::cout;
using std::cin;
using std::endl;
void University::printAllBuildings() {
cout << " Building Details : " << endl;
for (int j = 0; j < buildings.size(); j++) {
buildings[j].printBuilding();
}
}
void University::printAllPersonsRecord() {
cout << " Persons Details : " << endl;
for (int i = 0; i < persons.size(); i++) {
persons[i]->printPerson();
}
}
Building.h
#pragma once
#ifndef BUILDING_H
#define BUILDING_H
#include <iostream>
#include <vector>
#include <string>
#include "Person.h"
class Building {
public:
string name;
int size;
string address;
public:
void printBuilding();
};
#endif;
Building.cpp
#include "Building.h"
#include <iostream>
#include <vector>
#include <string>
using std::string;
using std::cout;
using std::cin;
using std::endl;
void Building::printBuilding() {
cout << " Name : " << name << " Address : " << address << endl;
}
main.cpp
#include "University.h"
#include "Person.h"
#include "Student.h"
#include "Instructor.h"
#include <iostream>
#include <vector>
#include <string>
using std::string;
using std::cout;
using std::cin;
using std::endl;
int main() {
Student student;
Instructor instructor;
student.setName("deepak");
student.setAge(12);
student.setGPA(12.0);
instructor.setName("rajdev");
instructor.setAge(23);
instructor.setRating(5.0);
Building building;
building.name = "block1";
building.size = 2000;
building.address = "noida sector-2";
Building building2;
building2.name = "block2";
building2.size = 4000;
building2.address = "noida sector-2";
University university;
university.name = "Oregon State University";
university.persons.emplace_back(&student);
university.persons.emplace_back(&instructor);
university.buildings.push_back(building);
university.buildings.push_back(building2);
university.printAllBuildings();
university.printAllPersonsRecord();
int choice;
bool isValidMainChoice = false;
while (!isValidMainChoice) {
cout << "Kindly choose one of the option from follwoing list of operations or Menu" << endl;
cout << "1 : Prints names of all the buildings" << endl;
cout << "2 : Prints names of everybody at the university" << endl;
cout << "3 : Choose a person to do work" << endl;
cout << "4 : Exit the program" << endl;
cin >> choice;
cout << "The value you entered is " << choice << endl;
if (choice == 1) {
university.printAllBuildings();
}
else if (choice == 2) {
university.printAllPersonsRecord();
}
else if (choice == 3) {
int personChoice;
bool isInputValid = false;
while (!isInputValid) {
cout << "Kindly choose the one of the following option to provide person's details." << endl;
cout << "5 : Student" << endl;
cout << "6 : Instructor" << endl;
cin >> personChoice;
if (personChoice == 5) {
isInputValid = true;
string studentName;
bool isValidName = false;
while (!isValidName) {
cout << " Kindly enter Name of the student :" << endl;
cin >> studentName;
if (studentName.length() == 0) {
cout << " Name must not be blank. Kindly re-enter the student's name." << endl;
}
else {
isValidName = true;
}
}
int age1 = 0;
bool isValidAge1 = false;
while (!isValidAge1) {
cout << " Kindly enter age of the student :" << endl;
cin >> age1;
if (age1 < 0 || age1 > 100) {
cout << " Age must be geter than 0 or lessa then 100. Kindly re-enter the student's age." << endl;
}
else {
isValidAge1 = true;
}
}
float gpa;
bool isValidGPA = false;
while (!isValidGPA) {
cout << " Kindly enter GPA of the student :" << endl;
cin >> gpa;
if (gpa < 0.0 || gpa > 4.0) {
cout << " GPA must be geter than 0.0 or less then 4.0. Kindly re-enter the Student GPA." << endl;
isValidGPA = false;
}
else {
isValidGPA = true;
}
}
Student student;
student.setName(studentName);
student.setAge(age1);
student.setGPA(gpa);
university.persons.emplace_back(&student);
university.printAllPersonsRecord();
}
else if (personChoice == 6) {
isInputValid = true;
string instructorName;
bool isValidName = false;
while (!isValidName) {
cout << " Kindly enter Name of the instructor :" << endl;
cin >> instructorName;
if (instructorName.length() == 0) {
cout << " Name must not be blank. Kindly re-enter the instructor's name." << endl;
}
else {
isValidName = true;
}
}
float rating;
bool isValidRating = false;
while (!isValidRating) {
cout << " Kindly enter rating of the instructor :" << endl;
cin >> rating;
if (rating < 0.0 || rating > 5.5) {
cout << " rating must be geter than 0.0 or less then 5.5. Kindly re-enter the instructor rating." << endl;
isValidRating = false;
}
else {
isValidRating = true;
}
}
int age2 = 0;
bool isValidAge2 = false;
while (!isValidAge2) {
cout << " Kindly enter age of the instructor :" << endl;
cin >> age2;
if (age2 < 0 || age2 > 100) {
cout << " Age must be geter than 0 or lessa then 100. Kindly re-enter the instructor's age." << endl;
}
else {
isValidAge2 = true;
}
}
Instructor instructor;
instructor.setName(instructorName);
instructor.setAge(age2);
instructor.setRating(rating);
university.persons.emplace_back(&instructor);
}
else {
cout << "The value you entered is incorrct.Please r-enter the values." << endl;
}
}
}
else if (choice == 4) {
isValidMainChoice = true;
cout << " You are exits from system. Thanks You !!" << endl;
}
}
return 0;
};

Please modify all your code for setter
void Person::setName(string name) {
//before-edit: name = name;
this->name = name; //OR Person::name = name;
}
As the local string name parameter and your class variable are the same, you expect the parameter are passed correctly, but it doesn't.

Related

Undefined reference to Artist::Artist and Artwork::Artwork [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 5 months ago.
I'm new to this multi-file class stuff and I've got an undefined reference for both of my classes and I think it has something to do with my initialization and default constructor but honestly have no clue if any of this is correct at all. Any help is greatly appreciated.
main.cpp
#include "Artist.h"
#include "Artwork.h"
#include <iostream>
#include <string>
using namespace std;
int main() {
string userTitle, userArtistName;
int yearCreated, userBirthYear, userDeathYear;
getline(cin, userArtistName);
cin >> userBirthYear;
cin.ignore();
cin >> userDeathYear;
cin.ignore();
getline(cin, userTitle);
cin >> yearCreated;
cin.ignore();
Artist userArtist = Artist(userArtistName, userBirthYear, userDeathYear);
Artwork newArtwork = Artwork(userTitle, yearCreated, userArtist);
newArtwork.PrintInfo();
}
Artist.h
#ifndef ARTISTH
#define ARTISTH
#include <string>
using namespace std;
class Artist{
public:
Artist();
Artist(string artistName, int birthYear, int deathYear);
string GetName() const;
int GetBirthYear() const;
int GetDeathYear() const;
void PrintInfo() const;
private:
string artistName;
int birthYear;
int deathYear;
};
#endif
Artist.cpp
#include "Artist.h"
#include <iostream>
#include <string>
using namespace std;
Artist::Artist()
{
artistName = "unknown";
birthYear = -1;
deathYear = -1;
}
string Artist::GetName() const
{
return artistName;
}
int Artist::GetBirthYear() const
{
return birthYear;
}
int Artist::GetDeathYear() const
{
return deathYear;
}
void Artist::PrintInfo() const
{
if(deathYear > 0 && birthYear > 0)
{
cout << "Artist: " << artistName <<" ("<< birthYear << " to "<< deathYear << ")" <<
endl;
}
else if(birthYear > 0 && deathYear < 0)
{
cout << "Artist: " << artistName <<" ("<< birthYear << " to present)" << endl;
}
else if(birthYear<0 && deathYear<0)
{
cout << "Artist: " << artistName << " (unknown)" << endl;
}
}
Artwork.h
#ifndef ARTWORKH
#define ARTWORKH
#include "Artist.h"
class Artwork{
public:
Artwork();
Artwork(string title, int yearCreated, Artist artist);
string GetTitle();
int GetYearCreated();
void PrintInfo();
private:
string title;
int yearCreated;
Artist artist;
};
#endif
Artwork.cpp
#include "Artwork.h"
#include <iostream>
Artwork::Artwork()
{
cout <<"Artwork has started." << endl;
title = "unknown";
yearCreated = -1;
Artist artist(); //here im not sure how to initialize an object inside of an object
}
string Artwork::GetTitle()
{
return title;
}
int Artwork::GetYearCreated()
{
return yearCreated;
}
void Artwork::PrintInfo()
{
artist.PrintInfo();
cout << "Title: " << title << ", " << yearCreated << endl;
}
I was correct, i needed to initialize both a default(no input parameters) constructor and a constructor with input parameters.
to correctly write a default and parameter constructor, do this
Artwork::Artwork(string n, int y, Artist a)
{
title = n;
yearCreated = y;
artist = a;
}//constructor with given input
Artwork::Artwork()
{
title = "unknown";
yearCreated = -1;
}//if input is not given for any fields, refer to this constructor
Notice that the default constructor does not have an object, I'm honestly not sure if there is a way to initialize a blank object and if so, why that isn't necessary.
The Artist constructor looks the same,
Artist::Artist(string name, int birth, int death)
{
artistName = name;
birthYear = birth;
deathYear = death;
}
Artist::Artist()
{
artistName = "unknown";
birthYear = -1;
deathYear = -1;
}

Sorting a Class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
So, I am learning about classes in C++, I created two classes, one for a University that contains a list of class Students, i managed to create students, and introduce some values to the classes, but now i want to sort the class students by student number, i tryed using the sort function, but im not succeeding. I will leave my code bellow, please give some good tips and advises, so I can improve my code. thanks
main.css
#include <iostream>
#include "university.h"
#include "students.h"
using namespace std;
int main() {
university univ = university();
return 0;
}
university.h
#pragma once
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
#include "students.h"
using namespace std;
class university
{
private:
list<students> lstudents;
list<students>::iterator itstudents;
public:
university();
void setStudents(list<students> lstudents);
void registerStudent();
void list();
void average();
//void sortstudents();
};
university.cpp
#include "university.h"
using namespace std;
university::university() { //constructor
string resp = "s";
int op;
bool out = true;
cout << "Enter Students:" << endl;
while (resp != "n")
{
this->registerStudent();
cout << "Continue inserting? (s/n)" << endl;
cin >> out;
cin.ignore();
}
while (out)
{
cout << "What you Want to do? (1- List Students 2- Sudent Average 3- Sort Students by Number 4- Leave)" << endl;
cin >> op;
switch (op)
{
case 1:
this->list();
break;
case 2:
this->average();
break;
/*case 3:
this->sortStudents();
break;*/
case 4:
out = false;
break;
};
}
}
void university::setStudents(list<students> lstudents) {
this->lstudents = lstudents;
}
void university::registerStudent()
{
lstudents.push_back(students());
}
void university::list()
{
int sum = 0;
cout << "------------------------- LIST STUDENTS -------------------------------\n\n";
cout << left << setw(11) << "Number"
<< left << setw(30) << "Name"
<< left << setw(30) << "Course"
<< left << setw(10) << "Average";
cout << "\n";
for (itstudents = lstudents.begin(); itstudents != lstudents.end(); itstudents++)
{
(*itstudents).list();
++sum;
}
//cout << "Total de pacientes:" << somatorio << endl;
//somatorio = 0;
}
void university::average()
{
int sum = 0;
double average = 0;
for (itstudents = lstudents.begin(); itstudents != lstudents.end(); itstudents++)
{
average += (*itstudents).getaverage();
++sum;
}
cout << "Average:" << average / sum << endl;
}
//void university::sortstudents() {
// sort(lstudents.begin(), lstudents.end(), &students::compare);
//}
students.h
as you can see the commented code is my attempts on sorting the class student my number
#pragma once
#include <iomanip>
#include <algorithm>
#include <list>
#include "university.h"
using namespace std;
class students {
private:
std::string name;
std::string course;
int number;
double average;
public:
//friend bool operator<(estudantes& left,estudantes& right) { return left.matricula < right.matricula; };
students();
void list();
double getaverage();
int getnumber();
//bool compare(estudantes a, estudantes b);
};
students.cpp
#include "students.h"
students::students() {
cout << "Name: ";
getline(cin, name);
cout << "Course: ";
getline(cin, course);
cout << "Number: ";
cin >> this->number;
cout << "Average: ";
cin >> this->average;
}
void students::list() {
cout << left << setw(11) << number;
cout << left << setw(30) << name;
cout << left << setw(30) << course;
cout << left << setw(10) << average << endl;
}
double students::getaverage() {
return average;
}
int students::getnumber() {
return number;
}
//bool estudantes::compare(student a, student b) {
//
// if (a.number < b.number)
// return 1;
// else
// return 0;
//}
Made it selfcontained and fixed. I'll post and then aexplain as surely people will have closed the question too soon:
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <list>
#include <string>
class students {
private:
std::string name;
std::string course;
int number;
double average;
public:
// friend bool operator<(students& left,students& right) { return
// left.matricula < right.matricula; };
students();
void list();
double getaverage();
int getnumber();
static bool compare(students const& a, students const& b);
};
students::students()
{
std::cout << "Name: "; getline(std::cin, name);
std::cout << "Course: "; getline(std::cin, course);
std::cout << "Number: "; std::cin >> this->number;
std::cout << "Average: "; std::cin >> this->average;
}
void students::list() {
std::cout << std::left << std::setw(11) << number;
std::cout << std::left << std::setw(30) << name;
std::cout << std::left << std::setw(30) << course;
std::cout << std::left << std::setw(10) << average << std::endl;
}
double students::getaverage() {
return average;
}
int students::getnumber() {
return number;
}
bool students::compare(students const& a, students const& b) {
return a.number > b.number;
}
class university {
private:
std::list<students> lstudents;
std::list<students>::iterator itstudents;
public:
university();
void setStudents(std::list<students> lstudents);
void registerStudent();
void list();
void average();
void sortStudents();
};
university::university() // constructor
{
std::string resp = "s";
int op;
bool out = true;
std::cout << "Enter Students:" << std::endl;
while (resp != "n") {
this->registerStudent();
std::cout << "Continue inserting? (s/n)" << std::endl;
std::cin >> out;
std::cin.ignore();
}
while (out) {
std::cout << "What you Want to do? (1- List Students 2- Sudent Average "
"3- Sort Students by Number 4- Leave)"
<< std::endl;
std::cin >> op;
switch (op) {
case 1: this->list(); break;
case 2:
this->average();
break;
case 3: this->sortStudents(); break;
case 4: out = false; break;
};
}
}
void university::setStudents(std::list<students> lstudents) {
this->lstudents = lstudents;
}
void university::registerStudent()
{
lstudents.push_back(students());
}
void university::list()
{
int sum = 0;
std::cout << "------------------------- LIST STUDENTS -------------------------------\n\n";
std::cout << std::left << std::setw(11) << "Number"
<< std::left << std::setw(30) << "Name"
<< std::left << std::setw(30) << "Course"
<< std::left << std::setw(10) << "Average";
std::cout << "\n";
for (itstudents = lstudents.begin(); itstudents != lstudents.end(); itstudents++)
{
(*itstudents).list();
++sum;
}
//std::cout << "Total de pacientes:" << somatorio << std::endl;
//somatorio = 0;
}
void university::average()
{
int sum = 0;
double average = 0;
for (itstudents = lstudents.begin(); itstudents != lstudents.end(); itstudents++)
{
average += (*itstudents).getaverage();
++sum;
}
std::cout << "Average:" << average / sum << std::endl;
}
void university::sortStudents() {
lstudents.sort(&students::compare);
}
int main() {
university univ = university();
return 0;
}
Explanation
There were a number of issues.
students::compare was a non-static member function, meaning it can only be called on an instance of student. To have a 2-argument sort predicate as required, simply making it static can work
The implementation could be much more idiomatic:
bool students::compare(students const& a, students const& b) {
return a.number > b.number;
}
That avoids the C-ism of using 1 as if it were true, and the useless if/else
You used std::sort but it requires random access iterators. std::list doesn't provide that. For that reason std::list::sort exists:
void university::sortStudents() {
lstudents.sort(&students::compare);
}
Among many other style issues:
don't using namespace std;
don't do side-effects in constructors?
error-check IO
avoid division by zero (e.g. in average()

Undefined Symbol in inherited classes for member Functions C++

So I'm writing a Manager class which inherits from SalariedEmployee which inherits from Employee. I have the employee.h header file and employee.cpp header file and also for salariedemployee as shown below.
I cant seem to understand why I get the following errors when I try to compile the code of
Undefined symbol: employeessavitch::SalariedEmployee::SalariedEmployee()
Undefined symbol: employeessavitch::SalariedEmployee::SalariedEmployee()
Undefined symbol: employeessavitch::SalariedEmployee::get_salary() const
Undefined symbol: employeessavitch::Employee::get_ssn() const
Undefined symbol: employeessavitch::Employee::get_name() const
Here are my files
employee.h
#ifndef employee_h
#define employee_h
#include <string>
#include "employee.h"
using namespace std;
namespace employeessavitch
{
class Employee
{
public:
Employee();
Employee(string the_name, string the_ssn);
string get_name( ) const;
string get_ssn( ) const;
double get_net_pay( ) const;
void set_name(string new_name);
void set_ssn(string new_ssn);
void set_net_pay(double new_net_pay);
void print_check( ) const;
protected:
string name;
string ssn;
double net_pay;
};
}
#endif /* employee_h */
employee.cpp
#include <string>
#include <cstring>
#include <stdio.h>
#include <cstdlib>
#include <iostream>
#include "employee.h"
using namespace std;
namespace employeessavitch
{
Employee::Employee(): name("No name yet"), ssn("No number yet"), net_pay(0)
{
//deliberately empty
}
Employee::Employee(string the_name, string the_ssn)
{
//deliberately empty
}
Employee::Employee(string the_name, string the_number): name(the_name), ssn(the_number), net_pay(0)
{
//deliberately empty
}
string Employee::get_name() const
{
return name;
}
string Employee::get_ssn() const
{
return ssn;
}
double Employee::get_net_pay() const
{
return net_pay;
}
void Employee::set_name(string new_name)
{
name = new_name;
}
void Employee::set_ssn(string new_ssn)
{
ssn = new_ssn;
}
void Employee::set_net_pay (double new_net_pay)
{
net_pay = new_net_pay;
}
void Employee::print_check( ) const
{
cout << "\nERROR: print_check FUNCTION CALLED FOR AN \n"
<< "UNDIFFERENTIATED EMPLOYEE. Aborting the program.\n"
<< "Check with the author of the program about this bug.\n";
exit(1);
}
}//employeessavitch
salariedemployee.h
#ifndef salariedemployee_h
#define salariedemployee_h
#include <string>
#include "employee.h"
#include "salariedemployee.h"
namespace employeessavitch
{
class SalariedEmployee : public Employee
{
public:
SalariedEmployee();
SalariedEmployee (string the_name, string the_ssn, double the_weekly_salary);
double get_salary() const;
void set_salary(double new_salary);
void print_check();
protected:
double salary;//weekly
};
}//employeessavitch
#endif /* salariedemployee_h */
salariedemployee.cpp
#include <iostream>
#include <string>
#include <stdio.h>
#include "salariedemployee.h"
using namespace std;
namespace employeessavitch
{
SalariedEmployee::SalariedEmployee() //: Employee(), salary(0)
{
//deliberately empty
}
SalariedEmployee::SalariedEmployee(string the_name, string the_number, double the_weekly_salary)//: Employee(the_name, the_number), salary(the_weekly_salary)
{
//deliberately empty
}
double SalariedEmployee::get_salary() const
{
return salary;
}
void SalariedEmployee::set_salary(double new_salary)
{
salary = new_salary;
}
void SalariedEmployee::print_check()
{
set_net_pay(salary);
cout << "\n__________________________________________________\n";
cout << "Pay to the order of " << get_name( ) << endl;
cout << "The sum of " << get_net_pay( ) << " Dollars\n";
cout << "_________________________________________________\n";
cout << "Check Stub NOT NEGOTIABLE \n";
void SalariedEmployee::print_check()
{
set_net_pay(salary);
cout << "\n__________________________________________________\n";
cout << "Pay to the order of " << get_name( ) << endl;
cout << "The sum of " << get_net_pay( ) << " Dollars\n";
cout << "_________________________________________________\n";
cout << "Check Stub NOT NEGOTIABLE \n";
cout << "Employee Number: " << get_ssn( ) << endl;
cout << "Salaried Employee. Regular Pay: "
<< salary << endl;
cout << "_________________________________________________\n";
}
}//employeessavitch
main.cpp
#include <iostream>
#include <cstring>
#include <string>
#include <string.h>
#include <fstream>
#include "salariedemployee.h"
#include "employee.h"
using namespace std;
namespace employeessavitch
{
class Manager: public SalariedEmployee
{
public:
Manager();
~Manager();
void addReport(SalariedEmployee employee);
friend ostream& operator <<(ostream &outs, Manager manager);
private:
SalariedEmployee *reports;
int noReport;
};
Manager::Manager()
{
noReport = 0;
}
Manager::~Manager()
{
delete[] reports;
}
void Manager::addReport(SalariedEmployee employee)
{
SalariedEmployee *report = new SalariedEmployee[noReport+1];
for(int i = 0; i < noReport; i++)
{
report[i] = reports[i];
}
report[noReport+1] = employee;
delete[] reports;
}
ostream& operator <<(ostream &outs, Manager manager)
{
for(int i = 0; i < manager.noReport; i++)
{
outs << manager.reports[i].get_name() << endl;
outs << manager.reports[i].get_ssn() << endl;
outs << manager.reports[i].get_salary() << endl;
}
return outs;
}
}
int main()
{
cout << "hello world";
return 0;
}

C++ Inheritance vector problem (infinite looping+ question of using vector in other class)

I'm making a surface to let the user to input information and print it out.
And this is what it looks like.
main <- menu <- Reservation
<- BookingManager <- BookingRecord
And I create a vector vector<string> CompanyName in Reservation,
This is outputdataInfo() that add CompanyName,
void Reservation::outputdataInfo()
{
string CompName;
cout << "Company Name <-" << endl;
cin >> CompName;
Reservation::setCompanyName(string (CompName) );
cout << CompanyName.at(0) << endl;
// Use for test and it works
cout << CompanyName.size() << endl;
// Use for test and it works
cout << "End of Reservation, thank you." << endl;
}
The setter of CompanyName:(worked)
void Reservation::setCompanyName(const string& cn)
{this->CompanyName.push_back(cn);}
But now BookingRecord::outputdataInfo() wants to print Booking Record.
void BookingRecord::outputdataInfo()
{
cout << " ----- Booking Record -----" << endl;
Reservation::printBookingRecord();
}
And I wrote like this(unconfirm this is correct or not):
void Reservation::printBookingRecord() {
for (int i = 0; i < CompanyName.size(); i++) {
cout << " ---- Company ---- " << endl;
cout << "Name: " << CompanyName.at(i) << endl;
}
}
But CompanyName suddenly looks like it forget anything, or like reset the size.
The result is BookingRecord::outputdataInfo() is printing infinitly non-stop, but nothing happen to the Reservation::printBookingRecord(). This is weird beacuse there suppose no for-loop in BookingRecord::outputdataInfo().
And I wanna know how to print data with (Reservation::printBookingRecord() is called by BookingRecord::outputdataInfo(), but the vector is at "Reservation")
(or vector can be use in other classes)
Big thanks :)
Source Code (kinda bit long sry)
//
// main.cpp
//
#include <iostream>
#include <string>
#include <cstdlib>
#include <vector>
#include "Menu.h"
#include "Reservation.h"
#include "BookingManager.h"
using namespace std;
int main(int argc, const char* argv[]) {
Menu m;
Reservation R;
BookingManager BM;
char choice;
do {
choice = m.menu();
switch (choice)
{
case 'R': case 'r':
R.outputdataInfo();
break;
case 'B': case 'b':
BM.outputdataInfo();
break;
default:
cout << "Invalid Alphabet. Please try again." << endl;
break;
}
} while (choice == 'R' || choice == 'r' || choice == 'B' || choice == 'b');
return 0;
}
//.....................
// Menu.h
//
#include <iostream>
#ifndef Menu_h
#define Menu_h
class Menu {
public: //Accessibility as public
char option;
char menu();
};
#endif
//.....................
// Menu.cpp
//
#include <iostream>
#include "Menu.h"
using namespace std;
char Menu::menu() {
cout << "" << endl;
cout << " BNC Exhibition Tour in European Cities" << endl;
cout << " Exhibition Recruitment " << endl;
cout << " " << endl;
cout << "Please type:" << endl;
cout << "R -> for Reservation Page" << endl;
cout << "B -> for Booking Manager Page" << endl;
cout << "And Press ENTER." << endl;
cin >> option;
cout << "" << endl;
return option;
}
//.............................
// Reservation.h
//
#include <iostream>
#include <vector>
using namespace std;
#ifndef Reservation_h
#define Reservation_h
class Reservation {
private:
vector<string> CompanyName;
public: //Accessibility as public
void outputdataInfo();
void setCompanyName(const string& cn);
Reservation();
~Reservation();
void printBookingRecord();
};
#endif
//.....................................
// Reservation.cpp
//
#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <vector>
using namespace std;
#include "Reservation.h"
void Reservation::outputdataInfo()
{
cout << "Please input detail information first :" << endl;
string CompName;
cout << "Company Name <-" << endl;
cin >> CompName;
Reservation::setCompanyName(string (CompName) );
cout << CompanyName.at(0) << endl; //it works
cout << CompanyName.size() << endl; //it works
cout << "End of Reservation, thank you." << endl;
}
//////////////////////// S E T T E R ////////////////////
void Reservation::setCompanyName(const string& cn)
{
this->CompanyName.push_back(cn);
}
//////////////////////// S E T T E R ////////////////////
Reservation::Reservation() {}
Reservation::~Reservation() {}
/////////////////////// P R I N T ///////////////////////
void Reservation::printBookingRecord() {
for (int i = 0; i < CompanyName.size(); i++) {
cout << " ---- Company ---- " << endl;
cout << "Name: " << CompanyName.at(i) << endl;
}
}
//.............................
// BookingManager.h
//
#include <iostream>
#include <vector>
#ifndef BookingManager_h
#define BookingManager_h
class BookingManager {
public: //Accessibility as public
char option;
void outputdataInfo();
};
//..........................................
// BookingManager.cpp
//
#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <vector>
#include "BookingManager.h"
#include "BookingRecord.h"
using namespace std;
void BookingManager::outputdataInfo() {
BookingRecord BR;
cout << "" << endl;
cout << " ----- Booking Manager -----" << endl;
cout << "" << endl;
cout << "Please type:" << endl;
cout << "B -> for Booking Record" << endl;
cout << "And Press ENTER." << endl;
cin >> option;
cout << "" << endl;
do {
switch (option)
{
case 'B': case 'b':
BR.outputdataInfo();
break;
default:
cout << "Invalid Alphabet. Please try again." << endl;
break;
}
} while (option == 'B' || option == 'b');
}
#endif
//...........................................
// BookingRecord.h
//
#include <iostream>
#include <vector>
#include "Reservation.h"
#ifndef BookingRecord_h
#define BookingRecord_h
class BookingRecord : public Reservation {
public: //Accessibility as public
void outputdataInfo();
};
#endif
//..........................................
// BookingRecord.cpp
//
#include <iostream>
#include <string>
#include <vector>
#include "Reservation.h"
#include "BookingRecord.h"
void BookingRecord::outputdataInfo()
{
cout << "" << endl;
cout << " ----- Booking Record -----" << endl;
cout << "" << endl;
cout << " Print all the information..." << endl;
Reservation::printBookingRecord();
}
// END
So you have two CompanyNames in your code.
One is here, part of the R variable.
int main(int argc, const char* argv[]) {
Menu m;
Reservation R;
And the other is here
void BookingManager::outputdataInfo() {
BookingRecord BR;
BookingRecord derives from Reservation, so it also contains a CompanyName.
I think it's pretty clear that you are adding a name to the CompanyName in R in main but printing out the CompanyName in BR in BookingManager::outputdataInfo.
The class design looks wrong to me.For instance there's a lack of parameters to your methods. Surely BookingManager::outputdataInfo should take a BookingRecord as a parameter to allow the caller to specify which BookingRecord they want to output. Just declaring a BookingRecord as a local variable in BookingManager::outputdataInfo doesn't make any sense.
Before you rush to write a lot of code, try and think about the design of your classes. How the different classes should relate to each other, what member variables they need, what methods they need, what parameters and return types those methods need. Think about this in terms of how your classes model the real world, not in terms of how you are going to implement functionality. That comes later, get the design right first.

Class Header , string does not name a type

Hi I'm trying to finish my homework. I have a compilation error when I try to separate a class, then call it later. But the whole test function works properly. It has the class within the whole text. Basically when i try to separate the class from the text, I have an error message.
#include <iostream>
#include<string>
using namespace std;
class Person
{
private:
string alpha;
int beta;
public:
Person(string Name, int Age)
{
alpha = Name;
beta = Age;
}
string getName()
{
return alpha;
}
int getAge()
{
if (beta < 0)
{ beta = 0;
cout << "Error. A negative age cannot be entered. " << endl;
}
if (beta > 120)
{
cout << "Damn you're old. How many heart transplants have you had? You Vampire " << endl;
}
return beta;
}
void setName(string alpha)
{
}
void setAge(int beta);
void display();
};
int main()
{
Person Lu("Jess ", 22);
Person Rose("Gary ", 49);
cout << Lu.getAge() << " " << Lu.getName() <<endl;
cout << Rose.getAge() << " " << Rose.getName() << endl;
return 0;
}`
But when i separate the class,:
#include <iostream>
#include <string>
class Person
{
private:
string alpha;
int beta;
public:
Person(string Name, int Age)
{
alpha = Name;
beta = Age;
}
string getName()
{
return alpha;
}
int getAge()
{
if (beta < 0)
{ beta = 0;
cout << "Error. A negative age cannot be entered. " << endl;
}
if (beta > 120)
{
cout << "Damn you're old. How many heart transplants have you had? You Vampire " << endl;
}
return beta;
}
void setName(string alpha)
{
}
void setAge(int beta);
void display();
};
Main file
#include <iostream>
#include "Person.h"
#include <string>
using namespace std;
int main()
{
Person Lu("Jess ", 22);
cout << Lu.getAge() << " " << Lu.getName() <<endl;
return 0;
}`
But when I separate the class i get an error in codeblocks. Please help.
You forgot to put using namespace std; in Person.h.
Also, you don't have any header guards on Person.h, which won't cause a problem in such a simple program, but will as soon as multiple files include Person.h.