So I was able to fix it, however, the operator doesn't seem to be comparing them both since I always get false. There seems to be an error with the pLoan where it is not comparing both of them.
My code is
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
//Vehicle Class
class Vehicle {
public:
Vehicle();
void setPrice(double a);
void setMpg(int a);
double getPrice() const;
int getMpg() const;
void printVehicle() const;
Vehicle(double price, int mpg);
private:
double price;
int mpg;
};
//Loan Class
class Loan {
public:
void setBank(string a);
void setLoan(double a);
string getBank() const;
double getLoan() const;
void printLoan() const;
Loan(string bank = "", double loan = 0);
private:
string bank;
double loan;
};
//Car Class
class Car : public Vehicle {
public:
Car(double price = 0, int mpg = 0, string bank = "", double loan = 0, string name = "", int element = 0);
void setName(string a);
void setLoan(string b, double l, int element);
string getName() const;
void printFull() const;
void setNbrOfLoans(int a);
int getNbrOfLoans() const;
Loan* getpLoan() const;
~Car();
private:
string name;
Loan* pLoan;
int nbrOfLoans;
};
bool operator==(const Car &car1, const Car &car2) {
Loan* pLoan1 = car1.getpLoan();
Loan* pLoan2 = car2.getpLoan();
return ((car1.getPrice() == car2.getPrice()) && (car1.getMpg() == car2.getMpg()) && (car1.getName() == car2.getName())
&& (car1.getNbrOfLoans() == car2.getNbrOfLoans()) &&
(pLoan1[0].getBank() == pLoan2[0].getBank()) && (pLoan1[0].getLoan() == pLoan2[0].getLoan()));
}
//Main
int main() {
Car car1(24800, 22, "Citi", 21600, "Mustang", 1);
Car* pCar1 = &car1;
pCar1->setLoan("Citi", 21600, 0);
pCar1->printFull();
pCar1->setNbrOfLoans(1);
Car car2;
Car* pCar2 = &car2;
cout << boolalpha;
cout << "Enter the price of the car: ";
double price;
cin >> price;
pCar2->setPrice(price);
cout << "Enter the mpg: ";
int mpg;
cin >> mpg;
pCar2->setMpg(mpg);
cout << "Enter the name of the car: ";
string name;
cin >> name;
pCar2->setName(name);
string bank;
double loan;
int index;
cout << "Enter the amount of loans you obtained: ";
cin >> index;
pCar2->setNbrOfLoans(index);
for (int i = 0; i < index; i++)
{
cout << "Enter the name of bank " << i + 1 << ": ";
cin >> bank;
cout << "Enter the amount of loan " << i + 1 << ": ";
cin >> loan;
pCar2->setLoan(bank, loan, i);
}
if (pCar1 == pCar2)
cout << "Cars are the same. ";
else
cout << "Cars are not the same. ";
cout << endl;
pCar2->printFull();
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////
//Vehicle class function definitions
////////////////////////////////////////////////////////////////////////////////////////
Vehicle::Vehicle() {
price = 0;
mpg = 0;
}
Vehicle::Vehicle(double price, int mpg) {
price = price;
mpg = mpg;
}
void Vehicle::setPrice(double a) {
price = a;
}
void Vehicle::setMpg(int a) {
mpg = a;
}
double Vehicle::getPrice() const {
return price;
}
int Vehicle::getMpg() const {
return mpg;
}
void Vehicle::printVehicle() const {
cout << "Price: " << price << endl;
cout << "MPG: " << mpg << endl;
}
////////////////////////////////////////////////////////////////////////////////////////
//Loan Class function definitions
///////////////////////////////////////////////////////////////////////////////////////
Loan::Loan(string bank, double loan) {
Loan::bank = bank;
Loan::loan = loan;
}
void Loan::setBank(string a) {
bank = a;
}
void Loan::setLoan(double a) {
loan = a;
}
string Loan::getBank() const {
return bank;
}
double Loan::getLoan() const {
return loan;
}
void Loan::printLoan() const {
cout << "Bank: " << bank << endl;
cout << "Loan: " << loan << endl;
}
////////////////////////////////////////////////////////////////////////////////////
//Car Class function definitions
////////////////////////////////////////////////////////////////////////////////////
Car::Car(double price, int mpg, string bank, double loan, string name, int element) : Vehicle(price, mpg)
{
nbrOfLoans = element;
Car::name = name;
setMpg(mpg);
setPrice(price);
pLoan = new Loan[nbrOfLoans];
}
Loan* Car::getpLoan() const{
return pLoan;
}
void Car::setName(string a) {
name = a;
}
void Car::setLoan(string b, double l, int element) {
pLoan[element].setBank(b);
pLoan[element].setLoan(l);
}
string Car::getName() const {
return name;
}
int Car::getNbrOfLoans() const {
return nbrOfLoans;
}
void Car::setNbrOfLoans(int a) {
nbrOfLoans = a;
if (pLoan != NULL)
delete[] pLoan;
pLoan = new Loan[nbrOfLoans];
}
void Car::printFull() const {
cout << endl << "Car name: " << name << endl;
cout << "Price: " << getPrice() << endl;
cout << "MPG: " << getMpg() << endl;
for (int i = 0; i < nbrOfLoans; i++)
{
cout << "Loan #" << i + 1 << "." << endl;
cout << "Bank: " << pLoan[i].getBank();
cout << endl;
cout << "Loan amount: " << pLoan[i].getLoan();
cout << endl;
}
}
Car::~Car() {
delete[] pLoan;
}
Output:
IS always cars are not the same even when they are
Your main code is not calling your operator ==:
if (pCar1 == pCar2)
cout << "Cars are the same. ";
else
cout << "Cars are not the same. ";
here you're comparing the two pointers. To compare the two pointed-to objects you need
if (*pCar1 == *pCar2) ...
One more error:
pCar1->setLoan("Citi", 21600, 0);
pCar1->printFull();
pCar1->setNbrOfLoans(1);
setNbrOfLoans must be located before setLoan:
pCar1->setNbrOfLoans(1);
pCar1->setLoan("Citi", 21600, 0);
pCar1->printFull();
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/
#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.
I am new to c++ and am working on a project for class. I know I that some of my functions are not correct. I am trying to get to a point to where I can at least see the output to continue working on it. I have included a brief description of that I am trying to do.
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class Employee
{
protected:
char* name[50];
public:
Employee()
{
}
Employee(char* name)
{
strcpy(name, name);
}
char* getName()
{
return *name;
}
void setName(char* name)
{
name = name;
}
/*virtual ~Employee()
{
delete[] name;
}*/
virtual void print() = 0;
};
class HourlyEmployee : public Employee
{
private:
float HourlySalary;
public:
HourlyEmployee()
{
HourlySalary = 0;
}
HourlyEmployee(char* name, float HourlySalary)
{
name = name;
HourlySalary = HourlySalary;
}
double getHourlySalary()
{
return HourlySalary;
//cout << "What is your Hourly Salary" << endl;
//cin >> HourlySalary;
}
void setHourlySalary(double HourlySalary)
{
}
void print()
{
cout << "Hourly Employee Name: " << &name << endl
<< "Salary: " << &HourlySalary << "per hour" << endl;
}
};
class SalariedEmployee : public Employee
{
private:
float MonthlySalary;
public:
SalariedEmployee()
{
MonthlySalary = 0;
}
SalariedEmployee(char* name, float MonthlySalary)
{
}
double getMonthlyySalary()
{
return MonthlySalary;
//cout << "What is your Hourly Salary" << endl;
//cin >> MonthlySalary;
}
void setMonthlySalary(double MonthlySalary)
{
}
void print()
{
cout << "Hourly Employee Name: " << name << endl
<< "Salary: " << MonthlySalary << "per month" << endl;
}
};
int main() {
SalariedEmployee* S = new SalariedEmployee();
SalariedEmployee S1("Joe Bob", '4500');
HourlyEmployee* H = new HourlyEmployee();
HourlyEmployee H1("Jim Bob", '20');
S1.print();
H1.print();
delete S, H;
system("pause");
return 0;
}
From the description of your exercise I concluded that you're asking for something like this:
#include <iostream>
using namespace std;
class Employee
{
protected:
char name[50];
public:
Employee()
{
}
Employee(char* name)
{
strncpy_s(this->name, 49, name, 49);
}
char* getName()
{
return this->name;
}
void setName(char *name)
{
strncpy_s(this->name, 49, name, 49);
}
virtual void print() = 0;
};
class HourlyEmployee : public Employee
{
private:
float hourlySalary;
public:
HourlyEmployee()
{
hourlySalary = 0;
}
HourlyEmployee(char* name, float HourlySalary)
{
strncpy_s(this->name, 49, name, 49);
this->hourlySalary = HourlySalary;
}
double getHourlySalary()
{
return hourlySalary;
//cout << "What is your Hourly Salary" << endl;
//cin >> HourlySalary;
}
void setHourlySalary(double HourlySalary)
{
this->hourlySalary = HourlySalary;
}
void print()
{
cout << "Hourly Employee Name: " << this->name << endl
<< "Salary: " << hourlySalary << " per hour" << endl;
}
};
class SalariedEmployee : public Employee
{
private:
float MonthlySalary;
public:
SalariedEmployee()
{
MonthlySalary = 0;
}
SalariedEmployee(char* name, float MonthlySalary)
{
strncpy_s(this->name, 49, name, 49);
this->MonthlySalary = MonthlySalary;
}
double getMonthlyySalary()
{
return MonthlySalary;
//cout << "What is your Hourly Salary" << endl;
//cin >> MonthlySalary;
}
void setMonthlySalary(double MonthlySalary)
{
this->MonthlySalary = MonthlySalary;
}
void print()
{
cout << "Hourly Employee Name: " << name << endl
<< "Salary: " << MonthlySalary << " per month" << endl;
}
};
int main()
{
Employee * employee[2];
employee[0] = new SalariedEmployee("Joe Bob", 4000);
employee[1] = new HourlyEmployee("Jim Bob", 20);
for (int i = 0; i < 2; i++)
{
employee[i]->print();
}
for (size_t i = 0; i < 2; i++)
{
delete employee[i];
}
system("pause");
return 0;
}
First off,your name variable's gotta be of type char[50],not *char[50]. So I used strncpy(or the safe function strncpy_s) to copy the name in our constructor. Since you're dealing with chars,you cannot assign it like you did in some parts of your code,like this name = name. And I used this->name because the variable names are identical. Next off,in your main function you gotta have the Employee class and then assign it to an HourlyEmployee and SalariedEmployee , because those are the principles of polymorphism. Hope that I have helped you and if you have any questions,don't hesitate to ask.
`