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.
Related
When I tried to convert it the class result can't get the data from class marks even if I made the data variables of marks public I don't know why. I also declared a object of class marks in result and then tried to access it but failed again I am new to coding so don't know all the syntax correctly your help will be of great use
#include <string.h>
#include <iostream>
using namespace std;
class student {
private:
int rl;
char nm[20];
public:
void read();
void display();
};
class marks : public student {
protected:
int s1;
int s2;
int s3;
public:
void getmarks();
void putmarks();
};
class result : public marks {
private:
int t;
float p;
char div[10];
public:
void process();
void printresult();
};
void student::read() {
cout << "enter Roll no and Name " << endl;
cin >> rl >> nm;
}
void student::display() {
cout << "Roll NO:" << rl << endl;
cout << "name : " << nm << endl;
}
void marks ::getmarks() {
cout << "enter three subject marks " << endl;
cin >> s1 >> s2 >> s3;
}
void marks ::putmarks() {
cout << "subject 1:" << s1 << endl;
cout << "subject 2 :" << s2 << endl;
cout << "subject 3:" << s3 << endl;
}
void result::process() {
t = s1 + s2 + s3;
p = t / 3.0;
p >= 60 ? strcpy(div, "first")
: p >= 50 ? strcpy(div, "second")
: strcpy(div, "third");
}
void result::printresult() {
cout << "total = " << t << endl;
cout << "per = " << p << "%" << endl;
cout << "div = " << div << endl;
}
int main(){
result x;
x.read();
x.getmarks();
x.process();
x.display();
x.putmarks();
x.printresult();
}
#include<iostream>
#include<string.h>
using namespace std;
class marks // parent class
{
protected:
int s1;
int s2;
int s3;
public:
void getmarks();
void putmarks();
};
class student : public marks // child class
{
private:
int rl;
char nm[20];
public:
void read();
void display();
};
class result : public marks// child class
{
private:
int t;
float p;
char div[10];
public:
void process();
void printresult();
};
void student::read()
{
cout<<"enter Roll no and Name "<<endl;
cin>>rl>>nm;
}
void student:: display()
{
cout <<"Roll NO:"<<rl<<endl;
cout<<"name : "<<nm<<endl;
}
void marks ::getmarks()
{
cout<<"enter three subject marks "<<endl;
cin>>s1>>s2>>s3;
}
void marks ::putmarks()
{
cout <<"subject 1:"<<s1<<endl;
cout<<"subject 2 :"<<s2<<endl;
cout <<"subject 3:"<<s3<<endl;
}
void result::process()
{
t= s1+s2+s3;
p = t/3.0;
p>=60?strcpy(div,"first"):p>=50?strcpy(div, "second"): strcpy(div,"third");
}
void result::printresult()
{
cout<<"total = "<<t<<endl;
cout<<"per = "<<p<<"%"<<endl;
cout<<"div = "<<div<<endl;
}
int main()
{
result x;
student y;
y.read();
x.getmarks();
x.process();
y.display();
x.putmarks();
x.printresult();
}
I'm doing self-study C++. I tried a program from the book, that would normally allocate a few objects of two derived classes dynamically using an array of pointers. I'm however preparing for an assignment where I'm not allowed to use pointers, so I made an alternative version without pointers.
The only error it gives me is C2259 "cannot instantiate abstract class", but I'm pretty sure I have overriden all the virtual functions.
Here is the header:
#ifndef ACCTBAC_H_
#define ACCTBAC_H_
#include <iostream>
#include <string>
// Abstract Base Class
class AcctABC
{
private:
std::string fullName;
long acctNum;
double balance;
protected:
struct Formatting
{
std::ios_base::fmtflags flag;
std::streamsize pr;
};
const std::string& FullName() const { return fullName; }
long AcctNum() const { return acctNum; }
Formatting SetFormat() const;
void Restore(Formatting& f) const;
public:
AcctABC(const std::string& s = "Nullbody", long an = -1, double bal = 0.0);
void Deposit(double amt);
virtual void Withdraw(double amt) = 0; // pure virtual function
double Balance() const { return balance; };
virtual void ViewAcct() const = 0; // pure virtual function
virtual ~AcctABC() {}
};
// Brass Account Class
class Brass : public AcctABC
{
public:
Brass(const std::string& s = "Nullbody", long an = -1, double bal = 0.0) : AcctABC(s, an, bal) {}
virtual void Withdraw(double amt);
virtual void ViewAcct() const;
virtual ~Brass() {}
};
// Brass Plus Account Class
class BrassPlus : public AcctABC
{
private:
double maxLoan;
double rate;
double owesBank;
public:
BrassPlus(const std::string& s = "Nullbody", long an = -1, double bal = 0.0, double ml = 500, double r = 0.10);
BrassPlus(const Brass& ba, double ml = 500, double r = 0.1);
virtual void ViewAcct() const;
virtual void Withdraw(double amt);
void ResetMax(double m) { maxLoan = m; }
void ResetRate(double r) { rate = r; }
void ResetOwes() { owesBank = 0; }
};
#endif
the class functions:
// acctabc.cpp -- bank account class methods
#include <iostream>
#include "acctabc.h"
using std::cout;
using std::ios_base;
using std::string;
// Abstract Base Class
AcctABC::AcctABC(const string& s, long an, double bal)
{
fullName = s;
acctNum = an;
balance = bal;
}
void AcctABC::Deposit(double amt)
{
if (amt < 0)
cout << "Negative deposit not allowed; "
<< "deposit is cancelled.\n";
else
balance += amt;
}
void AcctABC::Withdraw(double amt)
{
balance -= amt;
}
// protected methods for formatting
AcctABC::Formatting AcctABC::SetFormat() const
{
// set up ###.## format
Formatting f;
f.flag = cout.setf(ios_base::fixed, ios_base::floatfield);
f.pr = cout.precision(2);
return f;
}
void AcctABC::Restore(Formatting& f) const
{
cout.setf(f.flag, ios_base::floatfield);
cout.precision(f.pr);
}
// Brass methods
void Brass::Withdraw(double amt)
{
if (amt < 0)
cout << "Withdrawal amount must be positive; "
<< "withdrawal cancelled.\n";
else if (amt <= Balance())
AcctABC::Withdraw(amt);
else
cout << "Withdrawal amount of $" << amt
<< " exceeds your balance.\n"
<< "Withdrawal cancelled.\n";
}
void Brass::ViewAcct() const
{
Formatting f = SetFormat();
cout << "Brass Client: " << FullName() << "\n";
cout << "Account Number: " << AcctNum() << "\n";
cout << "Balance: $" << Balance() << "\n";
Restore(f);
}
// BrassPlus methods
BrassPlus::BrassPlus(const string& s, long an, double bal, double ml, double r) : AcctABC(s, an, bal)
{
maxLoan = ml;
owesBank = 0.0;
rate = r;
}
void BrassPlus::ViewAcct() const
{
Formatting f = SetFormat();
cout << "BrassPlus Client: " << FullName() << "\n";
cout << "Account Number: " << AcctNum() << "\n";
cout << "Balance: $" << Balance() << "\n";
cout << "Maximum loan: $" << maxLoan << "\n";
cout << "Owed to bank: $" << owesBank << "\n";
cout.precision(3);
cout << "Loan Rate: " << 100 * rate << "%\n";
Restore(f);
}
void BrassPlus::Withdraw(double amt)
{
Formatting f = SetFormat();
double bal = Balance();
if (amt <= bal)
AcctABC::Withdraw(amt);
else if (amt <= bal + maxLoan - owesBank)
{
double advance = amt - bal;
owesBank += advance * (1.0 + rate);
cout << "Bank Advance: $" << advance << "\n";
cout << "Finance charge: $" << advance * rate << "\n";
Deposit(advance);
AcctABC::Withdraw(amt);
}
else
cout << "Credit limit exceeded. Transaction cancelled.\n";
Restore(f);
}
and the main program:
// usebrass3.cpp -- polymorphic example using an abstract base class
#include <iostream>
#include <string>
#include "acctabc.h"
#include <vector>
const int CLIENTS = 4;
int main()
{
using std::cin;
using std::cout;
using std::vector;
using std::string;
vector<AcctABC> accounts(CLIENTS);
string temp;
long tempnum;
double tempbal;
char kind;
for (int i = 0; i < CLIENTS; i++)
{
cout << "Enter client's name: ";
getline(cin, temp);
cout << "Enter client's account number: ";
cin >> tempnum;
cout << "Enter opening balance: $";
cin >> tempbal;
cout << "Enter 1 for Brass Account: ";
while (cin >> kind && (kind != '1' && kind != '2'))
cout << "Enter either 1 or 2: ";
if (kind == 1)
accounts.push_back(Brass(temp, tempnum, tempbal));
else
{
double tmax, trate;
cout << "Enter the overdraft limit: $";
cin >> tmax;
cout << "Enter the interest rate "
<< "as a decimal fraction: ";
cin >> trate;
accounts.push_back(BrassPlus(temp, tempnum, tempbal, tmax, trate));
}
while (cin.get() != '\n')
continue;
}
cout << "\n";
for (int i = 0; i < CLIENTS; i++)
{
accounts[i].ViewAcct();
cout << "\n";
}
cout << "Done.\n";
return 0;
}
Here:
vector<AcctABC> accounts(CLIENTS);
you are trying to create a vector of AcctABC with CLIENTS default constructed AcctABC elements. But you cannot have AcctABC elements when the class is abstract. You also cannot have Brass elements in a vector of AcctABCs. You need pointers when you want to store a polymorphic type in a vector.
You cannot do this
vector<AcctABC> accounts(CLIENTS);
because it will make CLIENTS number of default constructed abstract base classes. You will also lose polymorphism and induce object slicing. Instead
vector<std::unique_ptr<AcctABC>> accounts;
then for example
accounts.push_back(std::make_unique<Brass>(temp, tempnum, tempbal));
I have an issue with a class i have created. When i compiling this so occures error message. Its basically all about char* to string. Here is my class
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
class Stock //klassdekleration
{
private:
char company[30];
int shares;
double share_val;
double total_val;
void set_tot() {total_val = shares * share_val;}
public:
Stock();
Stock(const char * co, int n = 0, double pr = 0.0);
void acquire(const char * co, int n, double pr);
void buy(int num,double price);
void sell(int num, double price);
void update(double price);
void show();
void compare( Stock );
const char * returncompany();
int returnshares();
};
#endif
// class function
//------------------------------------------------------------------------------------------------------
// constructor
Stock::Stock()
{
cout << "pre constructor is called \n";
strcpy(company, "namnlöst");
shares = 0;
share_val = 0;
total_val = 0;
}
Stock::Stock(const char * co, int n, double pr)
{
cout << " Constructor that use " << co << " is called \n";
strcpy("company", co);
company[29] = '\0';
shares = n;
share_val=pr;
set_tot();
}
//---------------------------------------------------------------------------------------------------------
// andra metoddefintioner
void Stock::acquire(const char * co, int n, double pr)
{
strcpy(company, co); //trunkera co om det behövs
company[29]='\0';
if (n<0)
{
cerr << "amount of shares cant be negative "
<< "share put to 0. \n";
shares = 0;
}
else
shares = n;
share_val = pr;
set_tot();
}
void Stock::buy(int num, double price)
{
if (num < 0)
{
cerr << "Amount of bought shares cant be negative. "
<< "transaction cancelled. ";
}
else
{
shares += num;
share_val = price;
set_tot();
}
}
void Stock::sell(int num, double price)
{
if (num < 0)
{
cerr << "amount of sold shares cant be negative. "
<< "Transaction cancelled. ";
}
else if (num > shares)
{
cerr << "cant sell more shares than you posses"
<< "Transaction cancelled. ";
}
else
{
shares -= num;
share_val = price;
set_tot();
}
}
void Stock::update(double price)
{
share_val = price;
set_tot();
}
void Stock::show()
{
cout << "Company: " << company
<< " Shares: " << shares << " \n"
<< " share value: $" << share_val
<< " Total value: $ " << total_val << " \n";
}
int Stock::returnshares()
{
return shares;
}
const char * Stock::returncompany()
{
return company;
}
void Stock::compare(Stock stock2)
{
if (shares < stock2.returnshares())
{
cout << "Company" << stock2.returncompany() << "have higher share value than" << company;
}
else
{
cout << "Company" << company << "have higher share value than" << stock2.returncompany();
}
}
I get this error message.
In constructor ‘Stock::Stock(const char*, int, double)’:
Stock_class.cc:60:23: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
strcpy("company", co);
any idea how i can fix this issue ?
kind regards
Hampus hahne
It seems fairly obvious, you wrote
strcpy("company", co);
when you meant
strcpy(company, co);
Attention to detail is required.
Also
company[29]='\0';
is unnecessary because strcpy always adds a '\0' character, so you don't need to add one as well.
i think in your code strcpy(company,co) will fix you problem.
usage of strcpy was not proper please follow below link for more details:
https://www.geeksforgeeks.org/strcpy-in-c-cpp/
i am trying to input a string in my code in c++ and when i run i always get the following error: Exception thrown at 0x0F5023F5 (msvcp140d.dll) in assignment-1.exe: 0xC0000005: Access violation writing location 0x00229C20. i will post my code below if anyone could help me that would be great.Please note that i already know that its a problem with me trying to access the memory location on which you dont have access to, i just dont know how to fix it.
HEADER FILE:
#ifndef item_H
#define item_h
class item
{
private:
//attributes
int itemID;
char itemName[20];
float itemcost;
float itemprice;
//utility function
float calcPrice();
public:
//constructor
item(int = 000, char[] = "itemUnknown", float = 0,float = 0);
//destructor
~item();
//set functions
void setAll(int, char[], float, float);
void setID(int);
void setName(char[]);
void setCost(float);
//get function
int getID();
float getcost();
float getprice();
void getname();
//print function
void print();
};
#endif
CPP:
#include "Dariush.h"
#include <iostream>
#include <iomanip>
#include<string>
using namespace std;
//constructor will set attributes
item::item(int ID, char n[] , float c,float p)
{
setID(ID);
setName(n);
setCost(c);
setAll(ID, n, c, p);
}
//destructor will print destroing two objects
item::~item()
{
cout << "destroing two objects : " << " " << itemName << " "
<< " & " << itemName << endl;
}
//set functions :
void item::setID(int ID)
{
cout << "please enter the item's ID : " << endl;
cin >> ID;
}
void item::setName(char n[])
{
cout << "please enter the item's name" << endl;
cin.ignore();
cin.getline(n, 20);
}
void item::setCost(float c)
{
cout << "please enter the item's cost : " << endl;
cin >> c;
}
void item::setAll(int ID, char n[], float c, float p)
{
itemID = (ID > 0 && ID < 999) ? ID : 0;
strcpy_s(itemName, n);
itemcost = (c > 0) ? c : 0;
calcPrice();
}
//get functions :
int item::getID()
{
return itemID;
}
float item::getcost()
{
return itemcost;
}
float item::getprice()
{
return itemprice;
}
void item::getname()
{
cout << itemName << endl;
}
//print function :
void item::print()
{
cout << "ID : " << itemID << endl
<< "Name : " << itemName << endl
<< "cost : " << itemcost << endl
<< "price : " << itemprice << endl;
}
// utility function for price callculation :
float item::calcPrice()
{
if (itemcost < 1000)
{
itemprice = itemcost + (itemcost*0.1);
}
else
itemprice = itemcost + (itemcost*0.2);
return itemprice;
}
MAIN.CPP:
#include "Dariush.h"
#include <iostream>
#include<string>
using namespace std ;
void main()
{
item i1;
item i2;
i1.print();
i2.print();
}
thanks for the assistance.
Lets take a closer look at these three function declarations:
item(int = 000, char[] = "itemUnknown", float = 0,float = 0);
void setAll(int, char[], float, float);
void setName(char[]);
The thing here is that the character "array" arguments you declare are not really arrays at all. Instead they are pointers. When declaring arguments, e.g. char n[] is actually translated by the compiler as char *n.
The constructor declaration makes the pointer point to the constant string literal "". And the important thing about constant string literals is that they are indeed constant. Trying to modify a string literal leads to undefined behavior. And change this literal is what you are trying to do with the cin.getline(n, 20) call in the setName function. Not only that, but you are also telling the cin.getline function to read more than fits in the string literal.
The simple solution is to have setName read into the member variable itemName instead.
There are many problems with this code, but the one that is causing the access violation is:
void item::setName(char n[])
{
cout << "please enter the item's name" << endl;
cin.ignore();
cin.getline(n, 20); //here
}
You should use cin.getline(itemName, 20); instead.
Also, to prevent such error in the future, declare arguments as char const n[] instead of char n[] - good compiler should display a warning when you use string literals with non-const pointer as argument.
#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.