I am trying to get my code to display the Ship class data, then use pointers to display the updated data after enter in console and set to the relevant variables in the CruiseShip and CragoShip classes. However, the program will ignore any new input and simply display the base class data again regardless of new data.
What is missing here?
using namespace std;
// -- Initialized the class 'Ship' -- //
class Ship {
public:
int yearBuilt;
string nameOfShip;
// Constructs the ship class and defines the values of the variables
Ship() {
yearBuilt = 0;
nameOfShip = "";
}
// Overloaded Constructor
Ship(int year, string name) {
Ship::yearBuilt = year;
Ship::nameOfShip = name;
year = 0;
name = "";
}
// Accessor Function for the year the ship was built
int getYearBuilt() const {
return yearBuilt;
}
// Accessor Function for the name of the ship
string getShipName() const {
return nameOfShip;
}
// Mutator Function to read input and set it to the value of yearBuilt
void setShipYear(int year) {
cout << " Enter Year: " << endl;
cin >> year;
year = yearBuilt;
cout << endl; // Spacing between printed data
}
// Mutator Function to read input and set it to the value of nameOfShip
void setShipName(string name) {
cout << " Enter Name: " << endl;
cin >> name;
name = nameOfShip;
cout << endl; // Spacing between printed data
}
// Virtual Print function to display the name of the ship and the year it was built
virtual void print() const {
cout << " Ship Name: " << nameOfShip << endl;
cout << " Year Built: " << yearBuilt << endl;
}
};
// -- Initializes the class 'CruiseShip' derived from Ship class -- //
class CruiseShip : public Ship
{
// Set the member variable for max number of passengers
int passengersMAX;
public:
//Constructor for CruiseShip, calls parent class
CruiseShip() : Ship() {
passengersMAX = 0;
}
//Overloaded Constructor
CruiseShip(int maximum, int year, string name) : Ship() {
CruiseShip::passengersMAX = maximum;
}
//Accessor
int getMaxPass() const {
return passengersMAX;
}
//Mutator
void setMaxPass(int maximum) {
cout << "Enter Passenger Max: " << endl;
cin >> maximum;
maximum = passengersMAX;
}
//Overriding Print Function
virtual void print() const override{
cout << " Ship Name: " << nameOfShip << endl;
cout << " Max number Of Passengers: " << passengersMAX << endl;
}
};
class CargoShip : public Ship
{
// Set the member variable for tonnage / capacity
int capacity;
public:
// Default Constructor
CargoShip() : Ship() {
capacity = 0;
}
//Overloaded constructor for CargoShip, calls parent class
CargoShip(int tonnage, string name) : Ship() {
CargoShip::capacity = tonnage;
}
// Accessor Function
int getCapacity() const {
return capacity;
}
//Mutator Function
void setCapacity(int tonnage) {
cout << " Enter max capacity: " << endl;
cin >> tonnage;
tonnage = capacity;
}
//Overriding Print Function
virtual void print() const override{
cout << " Name: " << nameOfShip << endl;
cout << " Capacity: " << capacity << endl;
}
};
int main()
{
// Pointer Array for Ships, listing the 3 ship classes
Ship *shipArray[3] = { new Ship(), new CruiseShip(), new CargoShip() };
// For loop to print the data for each of the 3 ships
for (int i = 0; i < 3; i++)
{
shipArray[i]->print();
cout << endl;
}
// Stores new data using the mutator functions within the class
shipArray[0]->setShipName("RMS Titanic");
shipArray[0]->setShipYear(1909);
// Pointers to the derived class, stores new data for functions in CruiseShip class
CruiseShip *csPoint = static_cast<CruiseShip*>(shipArray[1]);
csPoint->setShipName("HMS Victory");
csPoint->setMaxPass(850);
// Pointer to the derived class, stores new data for functions in CargoShip class
CargoShip *cgPoint = static_cast<CargoShip*>(shipArray[2]);
cgPoint->setShipName("HMHS Britannic");
cgPoint->setCapacity(48158);
//For loop to re-display updated data using base class pointers
for (int i = 0; i < 3; i++) {
shipArray[i]->print();
cout << endl;
}
return 0;
}
For starters these data members
int yearBuilt;
string nameOfShip;
should have the access specifier protected instead of public.
In this constructor
Ship(int year, string name) {
Ship::yearBuilt = year;
Ship::nameOfShip = name;
year = 0;
name = "";
}
the last two statements are redundant and does not make sense. Define the constructor like
Ship( int year, const string &name ) : yearBuilt( year ), nameOfShip( name )
{
}
It will be better to define these getters
// Accessor Function for the year the ship was built
int getYearBuilt() const {
return yearBuilt;
}
// Accessor Function for the name of the ship
string getShipName() const {
return nameOfShip;
}
like
// Accessor Function for the year the ship was built
const int & getYearBuilt() const {
return yearBuilt;
}
// Accessor Function for the name of the ship
const string & getShipName() const {
return nameOfShip;
}
These setters do not make sense. For example arguments are not used. And moreover you are trying to reassign arguments with data members.
// Mutator Function to read input and set it to the value of yearBuilt
void setShipYear(int year) {
cout << " Enter Year: " << endl;
cin >> year;
year = yearBuilt;
cout << endl; // Spacing between printed data
}
// Mutator Function to read input and set it to the value of nameOfShip
void setShipName(string name) {
cout << " Enter Name: " << endl;
cin >> name;
name = nameOfShip;
cout << endl; // Spacing between printed data
}
they should be defined at least like
// Mutator Function to read input and set it to the value of yearBuilt
void setShipYear(int year) {
yearBuilt = year;
}
// Mutator Function to read input and set it to the value of nameOfShip
void setShipName(string name) {
nameOfShip - name;
}
This constructor
//Overloaded Constructor
CruiseShip(int maximum, int year, string name) : Ship() {
CruiseShip::passengersMAX = maximum;
}
does not initialize data members of the base class with the passed arguments. It should be defined like
//Overloaded Constructor
CruiseShip(int maximum, int year, const string &name) : Ship(year, name ), passengersMAX( maximum )
{
}
This setter
//Mutator
void setMaxPass(int maximum) {
cout << "Enter Passenger Max: " << endl;
cin >> maximum;
maximum = passengersMAX;
}
should be defined like
//Mutator
void setMaxPass(int maximum) {
passengersMAX = maximum;
}
This constructor
CargoShip(int tonnage, string name) : Ship() {
CargoShip::capacity = tonnage;
}
does not initialize with the argument the base class sub-object. Moreover the data member yearBuilt does not have a corresponding argument.
So at least the constructor should be defined like
CargoShip(int tonnage, string name) : Ship( 0, name ), capacity( tonnage )
{
}
This setter
//Mutator Function
void setCapacity(int tonnage) {
cout << " Enter max capacity: " << endl;
cin >> tonnage;
tonnage = capacity;
}
should be defined like
//Mutator Function
void setCapacity(int tonnage) {
capacity = tonnage;
}
In these declaration
CruiseShip *csPoint = static_cast<CruiseShip*>(shipArray[1]);
//...
CargoShip *cgPoint = static_cast<CargoShip*>(shipArray[2]);
you should use reinterpret_cast
CruiseShip *csPoint = reinterpret_cast<CruiseShip*>(shipArray[1]);
//...
CargoShip *cgPoint = reinterpret_cast<CargoShip*>(shipArray[2]);
Related
This question already has answers here:
Undefined reference to static variable c++
(3 answers)
Closed 2 years ago.
I created a Class Student with instance data members
like studentname, studentaddress, studentrollno
i declared private static data member CollegeName that could be shared among all instances of class.
used promptfunction to take user input from the console
next functions to display student details.
Meanwhile resulting in below errors :
Meanwhile codes goes here:
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
int studentrollno;
string studentName;
string studentAddress;
static string CollegeName;
public:
void setRollNo(int rollno) {
studentrollno = rollno;
}
int getRollNo() {
return studentrollno;
}
void setName(string name) {
studentName = name;
}
string getName() {
return studentName;
}
void setAddress(string address) {
studentAddress = address;
}
string getAddress() {
return studentAddress;
}
static void setCollegeName(string collegename) {
CollegeName = collegename;
}
static string getCollegeName() {
return CollegeName;
}
void displayStudentDetails(); // member functions declare inside class Meanwhile it is defined
outside
static void show() {
cout << "this is static function " << endl;
}
};
// member functions define outside Student class
void Student :: displayStudentDetails() {
cout << "Student Name : " << getName() << " Student RollNo : " << getRollNo() << "Student Address
: " << getAddress() << "CollegeName: "<< getCollegeName() << endl;
}
void promptValues(Student &student) {
cout << "Enter the student Details " << endl;
cout << "Enter the details about student objects " << endl;
cout << endl;
int studentrollno;
string studentname , studentaddress ;
string collegename;
cout << "Enter the RollNo of the student " << endl;
cin >> studentrollno;
cout << "Enter the Name of the student " << endl;
cin >> studentname;
cout << endl;
cout << "Enter the address of the student " << endl;
cin >> studentaddress;
cout << endl;
cout << "Enter the collegeName of the student " << endl;
cin >> collegename;
student.setRollNo(studentrollno), student.setName(studentname), student.setAddress(studentaddress),
student.setCollegeName(collegename);
}
int main() {
Student student1, student2 , student3 , student4 , student5 ;
Student studentarrays[5] = { student1, student2, student3, student4, student5 };
Student studentmodel[5];
for (int i = 0; i < 5; i++) {
Student model;
model = studentarrays[i];
promptValues(model);
studentmodel[i] = model;
}
for (Student studentdetails : studentmodel) {
studentdetails.displayStudentDetails();
}
Student::show();
return 0;
}
You have omited the definition of the static member Student::CollegeName. It is only declared in the class, now you should define it after the class declaration with this:
std::string Student::CollegeName;
For more information see https://en.cppreference.com/w/cpp/language/static
#include <iostream>
#include <vector>
using namespace std;
class Flight;
class Time {
private :
int hour;
int minute;
public :
Time(int hour,int minute){
this->hour = hour;
this->minute = minute;
};
int getHour(){
return hour;
}
int getMinute(){
return minute;
}
};
class Passenger{
private:
string name;
int age;
public :
Passenger(string name , int age){
this->name = name;
this->age = age;
}
void printDetails(){
cout << "Name: " << name << "\t";
cout << "Age: " << age <<"\t";
}
friend void addPassenger(Passenger *p,int num,Flight f);
friend Flight;
};
class Flight {
private :
string id;
string destination;
Time *depart;
Time *arrival;
vector<Passenger> passengerList;
Passenger *pass;
public :
Flight(string id, string destination, Time *t, Time *a){
this->id = id;
this->destination = destination;
depart = t;
arrival = a;
id = 3;
};
void printInfo(){
cout<< "Flight Number : " << id << endl;
cout<< "Destination : " << destination << endl;
cout<< "Desparture : " << depart->getHour() << ":" << depart->getMinute()<< endl;
cout<< "Arrival : " << arrival->getHour() << ":" << arrival->getMinute() << endl;
}
void printList(){
cout << pass->name[0];
}
friend class Passenger;
friend void addPassenger(Passenger *p,int num,Flight f);
};
void addPassenger(Passenger *p,int num,Flight f){
// for(int i=0;i<num;i++){
// f.passengerList.push_back(p[i]);
f.pass->name = p->name;
// }
}
int main(){
int num_passenger;
int temp_age;
string temp_name;
vector<int> passenger_age;
vector<string> passenger_name;
Time t(2,4);
Time t2(2,3);
Flight ff("3","4",&t,&t2);
cout<< "Enter the number of passenger" << endl;
cin>> num_passenger;
cout<< endl;
Passenger *pas[num_passenger];
for(int i=0;i < num_passenger; i++){
cout<< "Enter the name of adult "<< i+1 << endl;
cin>> temp_name;
passenger_name.push_back(temp_name);
cout<< "Enter the age of adult "<< i+1 << endl;
cin>> temp_age;
passenger_age.push_back(temp_age);
}
for(int p=0; p < num_passenger; p++){
pas[p] = new Passenger(passenger_name[p],passenger_age[p]);
}
addPassenger(*pas,2,ff);
ff.printList();
return 0;
}
I need to pass array object of Passenger Class into private array object of Passenger Class that inside object of Flight Class through function addPassenger.
Everything compile fine, but I can't get printList(object Flight) work, it simply jumps out and terminates the console.
Sorry it quite complicated due to requirement of project.
Hope to have some helps, Thanks.
Problem 1
The main problem is at line
f.pass->name = p->name;
The source of the problem is that the member variable pass of Flight is not initialized properly and then you go on to use f.pass as though it is a valid pointer.
Problem 2
The function addPassenger takes a Flight object as input. When you call the function, the function gets a copy of the original Flight object. Any changes made to the Flight object in addPassenger are to the local copy, not the object from main.
With the following changes, I was able to run your program without any problem.
Changed the member of variable of Flight to:
string id;
string destination;
Time *depart;
Time *arrival;
vector<Passenger> passengerList;
Removed the member varible pass.
Changed the signature of addPassenger to.
void addPassenger(std::vector<Passenger> const& plist, Flight& f);
and changed its implementation to
void addPassenger(std::vector<Passenger> const& plist, Flight& f)
{
for(auto& p : plist ){
f.passengerList.push_back(p);
}
}
Changed the implementation of Flight::printList to:
void printList(){
for(auto& p : passengerList ){
cout << p.name << endl;
}
}
Changed the type of pas in main to:
std::vector<Passenger> pas;
Other things needed to be changed to account for these changes. Here's the complete program:
#include <iostream>
#include <vector>
using namespace std;
class Flight;
class Time {
private :
int hour;
int minute;
public :
Time(int hour,int minute){
this->hour = hour;
this->minute = minute;
};
int getHour(){
return hour;
}
int getMinute(){
return minute;
}
};
class Passenger{
private:
string name;
int age;
public :
Passenger(string name , int age){
this->name = name;
this->age = age;
}
void printDetails(){
cout << "Name: " << name << "\t";
cout << "Age: " << age <<"\t";
}
friend void addPassenger(std::vector<Passenger> const& plist, Flight& f);
friend Flight;
};
class Flight {
private :
string id;
string destination;
Time *depart;
Time *arrival;
vector<Passenger> passengerList;
public :
Flight(string id, string destination, Time *t, Time *a){
this->id = id;
this->destination = destination;
depart = t;
arrival = a;
id = 3;
};
void printInfo(){
cout<< "Flight Number : " << id << endl;
cout<< "Destination : " << destination << endl;
cout<< "Desparture : " << depart->getHour() << ":" << depart->getMinute()<< endl;
cout<< "Arrival : " << arrival->getHour() << ":" << arrival->getMinute() << endl;
}
void printList(){
for(auto& p : passengerList ){
cout << p.name << endl;
}
}
friend class Passenger;
friend void addPassenger(std::vector<Passenger> const& plist, Flight& f);
};
void addPassenger(std::vector<Passenger> const& plist, Flight& f)
{
for(auto& p : plist ){
f.passengerList.push_back(p);
}
}
int main(){
int num_passenger;
int temp_age;
string temp_name;
vector<int> passenger_age;
vector<string> passenger_name;
Time t(2,4);
Time t2(2,3);
Flight ff("3","4",&t,&t2);
cout<< "Enter the number of passenger" << endl;
cin>> num_passenger;
cout<< endl;
std::vector<Passenger> pas;
for(int i=0;i < num_passenger; i++){
cout<< "Enter the name of adult "<< i+1 << endl;
cin>> temp_name;
passenger_name.push_back(temp_name);
cout<< "Enter the age of adult "<< i+1 << endl;
cin>> temp_age;
passenger_age.push_back(temp_age);
}
for(int p=0; p < num_passenger; p++){
pas.push_back(Passenger(passenger_name[p],passenger_age[p]));
}
addPassenger(pas, ff);
ff.printList();
return 0;
}
See it working at http://ideone.com/Chttoe.
Im trying to create a percent savings program for a supermarket with 3 inherited classes (PersonData -> CustomerData -> PreferredCustomer). The entire program has to follow this UML diagram:
I am having problems with the third class; specifically initializing values in the first constructor of the class. Im getting an error message in visual studio: "redefinition of formal parameter Pa" and "redefinition of formal parameter "dl".
This is the constructor with the errors:
PreferredCustomer(string aLname, string aFname, string aAddress,
string aCity, string aState, int aZip, string aPhone, int cn,
bool ml, double Pa, double dl) // constructor 1
{
double Pa;
double dl;
}
The parameters in this third child constructor have been overloaded from the parent constructor. Arguments cn, ml, Pa, dl have all been added into this parameter.
I'm not sure why i am getting these errors? Also, should i be creating a virtual function or using pointers? Thank you for any help.
My program source code (for reference):
#include <iostream>
#include <string>
using namespace std;
class PersonData // PersonData parent class defined
{
private:
string lastName;
string firstName;
string address;
string city;
string state;
string phone;
int zip;
public:
PersonData() // Default Constructor initialization
{
lastName = " ";
firstName = " ";
address = " ";
city = " ";
state = " ";
zip = 0;
phone = " ";
}
PersonData(string aLname, string aFname, string aAddress, string aCity, string aState, int aZip, string aPhone) // Constructor 1
{
lastName = aLname;
firstName = aFname;
address = aAddress;
city = aCity;
state = aState;
zip = aZip;
phone = aPhone;
}
// Accesor Functions
string getLastName() const
{
return lastName;
}
string getFirstName() const
{
return firstName;
}
string getAddress() const
{
return address;
}
string getCity() const
{
return city;
}
string getState() const
{
return state;
}
int getZip() const
{
return zip;
}
string getPhone() const
{
return phone;
}
// Mutator Functions
void setLastName(string aLname)
{
lastName = aLname;
}
void setFirstName(string aFname)
{
firstName = aFname;
}
void setAddress(string aAddress)
{
address = aAddress;
}
void setCity(string aCity)
{
city = aCity;
}
void setState(string aState)
{
state = aState;
}
void setZip(int aZip)
{
zip = aZip;
}
void setPhone(string aPhone)
{
phone = aPhone;
}
};
class CustomerData :public PersonData // CustomerData child class of PersonData base class
{
private:
int customerNumber;
bool mailingList;
public:
CustomerData() // Default constructor
{
customerNumber = 0;
mailingList = 0;
}
CustomerData(int cNum, bool mailL) // Constructor 1
{
setCustomerNumber(cNum);
setMailingList(mailL);
}
// Accessor Functions for child class
int getCustomerNumber() const
{
return customerNumber;
}
bool getMailingList() const
{
if (mailingList != 0)
{
cout << "On Mailing List!: ";
return mailingList;
}
else (mailingList == 0);
{
cout << "Not on mailing list!: ";
return mailingList;
}
}
// Mutator Functions for child class
void setCustomerNumber(int cNum)
{
customerNumber = cNum;
}
void setMailingList(bool mailL)
{
mailingList = mailL;
}
};
class PreferredCustomer :public CustomerData // child class of CustomerData child class
{
private:
double purchasesAmount;
double discountLevel;
public:
PreferredCustomer() // default constructor
{
purchasesAmount = 0;
discountLevel = 0;
}
PreferredCustomer(string aLname, string aFname, string aAddress,
string aCity, string aState, int aZip, string aPhone, int cn,
bool ml, double Pa, double dl) // constructor 1
{
double Pa;
double dl;
}
// Mutator Functions
void setPurchasesAmount(double Pa)
{
purchasesAmount = Pa;
}
// Accessor Functions
double getPurchasesAmount() const
{
return purchasesAmount;
}
double getDiscountLevel() const
{
return discountLevel;
}
void addPurchase(double P) const
{
}
};
int main()
{
CustomerData Cdata; // for access of child class functions
PersonData Pdata; // for access of parent class functions
PreferredCustomer PCdata; // for access of preferred customer class functions
string temp1; // Temporary variable for string values
int temp2, // Temporary variable for integer values
max = 100, // For-loop maximum loop value
i; // i variable
bool temp3; // Temporary variable for bool values
for (i = 1; i <= max; i++)
{
// Input Data
cout << "Please input first Name: ";
getline(cin, temp1);
Pdata.setFirstName(temp1);
cout << "Please input last Name: ";
getline(cin, temp1);
Pdata.setLastName(temp1);
cout << "Please input address: ";
getline(cin, temp1);
Pdata.setAddress(temp1);
cout << "Please input city: ";
getline(cin, temp1);
Pdata.setCity(temp1);
cout << "Please input state: ";
getline(cin, temp1);
Pdata.setState(temp1);
cout << "Please input Zip code: ";
cin >> temp2;
Pdata.setZip(temp2);
cin.ignore(); // discards unread char from cin
cout << "Please input Phone Number: ";
getline(cin, temp1);
Pdata.setPhone(temp1);
cout << "Enter 1 to be included in mail list," << endl;
cout << "Enter 0 to not be included in mail list: ";
cin >> temp3;
Cdata.setMailingList(temp3);
Cdata.setCustomerNumber(i); // set customer number
cout << endl << endl;
cout << "Name: " << Pdata.getFirstName() << ", " << Pdata.getLastName() << " \n";
cout << "Customer Number: " << Cdata.getCustomerNumber() << "\n";
cout << "Address: " << Pdata.getAddress() << "\n";
cout << "City: " << Pdata.getCity() << "\n";
cout << "State: " << Pdata.getState() << "\n";
cout << "Phone: " << Pdata.getPhone() << "\n";
cout << "Zip: " << Pdata.getZip() << "\n";
cout << Cdata.getMailingList() << "\n";
cout << endl << endl;
cin.ignore(); // discards unread char from cin
}
char c;
cin >> c;
return 0;
}
A constructor's purpose is to take the parameters the are passed in and construct the object from the class declaration and initialize members as appropriate. It not only has to initialize the class but also all the base classes as well, this can be done by passing parameters to the base constructor(s).
In
PreferredCustomer(string aLname, string aFname, string aAddress,
string aCity, string aState, int aZip, string aPhone, int cn,
bool ml, double Pa, double dl) // constructor 1
{
double Pa;
double dl;
}
You aren't initializing anything
You are declaring two local parameters that match (and conflict with) the parameters passed in
You don't call the base's constructors (how most of the work is done)
PreferredCustomer(...) :CustomerData(...)
CustomerData(...) :PersonData(...)
You don't initialize this class's members
purchasesAmount = pa;
discountLevel = dl;
My output name is not being displayed in my program. I have been looking at the code and
I just can't find my error
input
name : John Dough
id : 123445
start date : 10312014
shift: 2
output
name : ^^^^^^ <<<< I am having problem my name not being displayed
id : 123445
start date : 10312014
shift : 2
code
//This program demostrates a class and a derived class with constructors.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Employee
{
private:
char EmpName;
int EmpNum;
int HireDate;
public:
void setEmpName(char);
void setEmpNum(int);
void setHireDate(int);
char getEmpName() const;
int getEmpNum() const;
int getHireDate() const;
Employee();
};
void Employee::setEmpName(char x)
{
EmpName = x;
}
void Employee::setEmpNum(int y)
{
EmpNum = y;
}
void Employee::setHireDate(int z)
{
HireDate = z;
}
char Employee::getEmpName() const
{
return EmpName;
}
int Employee::getEmpNum() const
{
return EmpNum;
}
int Employee::getHireDate() const
{
return HireDate;
}
Employee::Employee()
{
cout << "I will ask you some questions about an employee.\n\n";
}
class ProductionWorker : public Employee
{
private:
int Shift;
double HourlyPayRate;
public:
void setShift(int);
void setHourlyPayRate(double);
int getShift() const;
double getHourlyPayRate() const;
ProductionWorker();
};
void ProductionWorker::setShift(int a)
{
Shift = a;
}
void ProductionWorker::setHourlyPayRate(double b)
{
HourlyPayRate = b;
}
int ProductionWorker::getShift() const
{
return Shift;
}
double ProductionWorker::getHourlyPayRate() const
{
return HourlyPayRate;
}
ProductionWorker::ProductionWorker()
{
cout << "After answering the questions,\n";
cout << "I will display the employee's information.\n\n\n";
}
int main()
{
ProductionWorker info;
char name[100];
int num;
int date;
int shift;
double rate;
cout << "What is the employee's name? ";
cin.getline(name, 100);
cout << "What is the employee's number? ";
cin >> num;
cout << "What is the employee's hire date?\n";
cout << "(Month, day, and year without any slashes,\n";
cout << "dashes, commas, or other punctuation.)\n";
cout << "For example, January 14, 1983 would look like 01141983. ";
cin >> date;
cout << "Does the employee work shift 1 or shift 2? ";
cin >> shift;
cout << "How much does the employee make per hour? ";
cin >> rate;
info.setEmpName(name[100]);
info.setEmpNum(num);
info.setHireDate(date);
info.setShift(shift);
info.setHourlyPayRate(rate);
cout << "\n\nHere is the employee's data:\n\n";
cout << "Employee's Name: " << info.getEmpName() << endl;
cout << "Employee's Number: " << info.getEmpNum() << endl;
cout << "Employee's Hire Date: " << info.getHireDate() << endl;
cout << "Employee's Shift: " << info.getShift() << endl;
cout << setprecision(2) << fixed;
cout << "Employee's Hourly Pay Rate: $" << info.getHourlyPayRate() << endl << endl;
return 0;
}
This is wrong: you're accessing an out-of-range character instead of passing the array to the function
char name[100];
//.. initialize name..
info.setEmpName(name[100]); // Accesses the 100th character (out-of-range [0-99])
void Employee::setEmpName(char x)
{
EmpName = x;
}
I would go for using std::string by changing EmpName (also wrong, it's not a single character) to a std::string
class Employee
{
private:
string EmpName;
int EmpNum;
int HireDate;
public:
void setEmpName(std::string& name);
void setEmpNum(int);
void setHireDate(int);
string getEmpName() const;
int getEmpNum() const;
int getHireDate() const;
Employee();
};
Also don't forget to change char name[100] to a std::string in the main function.
Live Example
You can of course accomplish this also with char arrays, in that case if you intend to use a fixed-size array you could either pass it by reference or just copy the content of a pointer to the array into a memory array for Employee.
There are multiple problems with your code.
First, the data type of Employee::EmpName should not be char. It should be a char array or even better would be a std::string.
Second the parameter of the setEmpName function should be either a const char* or a const std::string&.
Third, the name variable should perhaps be a std::string instead of a char array. Of course if you make that change the parameter of the setEmpName function should be const std::string&.
Fourth, when calling the setEmpName function you should just call it as follows: info.setEmpName(name).
Next, you should use std::getline(cin, name) instead of cin.getline(name, 100).
I'm first correcting your mistakes and then giving you a better alternative solution.
The member of your class and the setter function's parameter are only a single char. Change them to arrays:
char EmpName[100];
and
void setEmpName(char[]);
and in the implementation, you need to copy the content of the given array to your member:
void Employee::setEmpName(char[] x) {
memcpy(EmpName, x, 100);
}
However, this is the C way to do this.
The C++ way to do this is to use std::string. For this, change the types of the member, the parameters in the setter and in the getter as well as the type in main to std::string. To read a std::string, use the free-standing overload of getline which only takes the stream and the string (but no count):
getline(cin, name);
This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 9 years ago.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
//In this section I create the class HotelRoom
class HotelRoom
{
protected:
HotelRoom(){}
char room_Number[4];
char* guestName;
double rate;
public:
HotelRoom(char Num[], double daily, char* name);
HotelRoom(const HotelRoom &);
~HotelRoom();
int Get_Capacity();
int Get_Status();
double Get_Rate();
const char* Get_Number();
const char* Get_Guest();
int Change_Status(int Stat);
};
HotelRoom::HotelRoom(char Num[], double daily, char* name)
{
strcpy_s(room_Number, 4, Num);
guestName = new char[strlen(name) + 1];
strcpy_s(guestName, 20, name);
rate = daily;
}
HotelRoom::HotelRoom(const HotelRoom& room_r)
{
strcpy_s(room_Number, room_r.room_Number);
guestName = new char[strlen(room_r.guestName) + 1];
strcpy_s(guestName, 20, room_r.guestName);
rate = room_r.rate;
}
HotelRoom::~HotelRoom()
{
cout << endl << endl;
cout << "Decunstructor Activated." << endl;
delete[] guestName;
}
double HotelRoom::Get_Rate()
{
return rate;
}
const char* HotelRoom::Get_Number()
{
return room_Number;
}
const char* HotelRoom::Get_Guest()
{
return guestName;
}
class DerivedGuestRoom : public HotelRoom
{
public:
DerivedGuestRoom(int max, int stat, int nights);
DerivedGuestRoom(const DerivedGuestRoom&);
~DerivedGuestRoom();
protected:
int capacity;
int status = 0; //0 if unoccupied
int days;
};
DerivedGuestRoom::DerivedGuestRoom(int max, int stat, int nights) : capacity(max), status(stat), days(nights)
{
cout << "data members set";
}
DerivedGuestRoom::~DerivedGuestRoom()
{
cout << "\ndecunstrucor";
}
class DerivedMeetingRoom : public HotelRoom
{
public:
DerivedMeetingRoom(int seat, int stat);
DerivedMeetingRoom(const DerivedMeetingRoom&);
~DerivedMeetingRoom();
protected:
int seats;
int status; //1 if booked for meeting 0 otherwise
};
DerivedMeetingRoom::DerivedMeetingRoom(int seat, int stat) : seats(seat), status(stat)
{
cout << "data members set";
}
DerivedMeetingRoom::~DerivedMeetingRoom()
{
cout << "\ndecunstrucor";
}
void Display_info(HotelRoom&);
HotelRoom* Create_Hotel();
int main()
{
cout << setprecision(2)
<< setiosflags(ios::fixed)
<< setiosflags(ios::showpoint);
HotelRoom* Hotel_Rooms[200];
int count = 0;
char response;
cout << endl;
cout << "Do you want to enter information about a hotel room?(Y/N): ";
response = cin.get();
cin.get();
while (toupper(response) == 'Y' && count < 10)
{
Hotel_Rooms[count] = Create_Hotel();
++count;
cout << endl;
cout << "Do you want to enter information about a hotel room?(Y/N): ";
response = cin.get();
cin.get();
}
//Display the accounts created
for (int i = 0; i < count; ++i)
Display_info(*Hotel_Rooms[i]);
for (int i = 0; i < count; ++i)
delete Hotel_Rooms[i];
cout << endl;
system("PAUSE");
return 0;
}
void Display_info(HotelRoom& room)
{
cout << "\n\nGuest's Name: " << room.Get_Guest() << endl << endl;
cout << "\nYour room number is " << room.Get_Number() << endl << endl;
cout << "\nDaily rate is: " << room.Get_Rate() << endl << endl;
cout << endl;
cout << endl;
}
HotelRoom* Create_Hotel()
{
//These are the variables that will be holding data then passed through objects
char roomNumber[4];
char guestName[20];
double dailyRate = 89.00;
HotelRoom* room_ptr;
//This portion asks for user input
cout << "\nEnter Guest information\n\n";
cout << "Enter the room number: ";
cin.getline(roomNumber, 4);
cout << "Enter the guest's name: ";
cin.getline(guestName, 20);
cout << endl;
cin.get(); //Clears input buffer
room_ptr = new HotelRoom(roomNumber, dailyRate, guestName);
return room_ptr;
}
I took out HotelRoom(); from parent class constructor and I removed from the child class constructors. I Now only have this error:
LearningOOP.exe has triggered a breakpoint.
Which I have never encountered this so not sure what it means.
You declared a default constructor:
class HotelRoom
{
public:
HotelRoom();
}
and there is no implementation for that default constructor method. You can change to:
class HotelRoom
{
public:
HotelRoom() {}
}
or implement HotelRoom:HotelRoom { } in your cpp file.
You haven't defined your default constructor for the HotelRoom class.
class HotelRoom
{
protected:
char room_Number[4];
char* guestName;
double rate;
public:
HotelRoom(); //< Not defined!
HotelRoom(char Num[], double daily, char* name);
HotelRoom(const HotelRoom &);
~HotelRoom();
int Get_Capacity();
int Get_Status();
double Get_Rate();
const char* Get_Number();
const char* Get_Guest();
int Change_Status(int Stat);
};
An "Unresolved external symbol" linker error means that you've declared and used a piece of code in your application, but you haven't defined it before using it.
EDIT (Based on your follow up comment below):
You can't take the constructor out because it's needed in other parts of your code. See this line in your code:
DerivedGuestRoom::DerivedGuestRoom(int max, int stat, int nights) : HotelRoom(), capacity(max), status(stat), days(nights)
// ^---------^
// |
// Using the default constructor.
DerivedMeetingRoom::DerivedMeetingRoom(int seat, int stat) : HotelRoom(), seats(seat), status(stat)
// ^---------^
// |
// And again here!
You either need to remove implement the default constructor for the HotelRoom class, or add parameters to your DerivedMeetingRoom and DerivedGuestRoom class constructors so that you can use the HotelRoom(char Num[], double daily, char* name) constructor.