Hello I'm a bit confused of this problem I'm currently practicing to enhance my Inheritance task in c++. Would you mine to help me.
My goal is to update the acct_balance variable which is from base class.
#include <iostream>
class Account{
public:
Account(double initial_balance)
{
if(initial_balance >= 0)
acct_balance = initial_balance;
else
std::cout << "Invalid Balance!" << std::endl;
}
void credit(double x)
{
acct_balance += x;
}
void debit(double x)
{
if(x <= acct_balance){
acct_balance -= x;
flagWidraw = true;
}
else
std::cout << "Debit amount exceeded account balance." << std::endl;
}
double getBalance()
{
return acct_balance;
}
public:
double acct_balance;
bool flagWidraw = false;
};
class SavingsAccount:public Account{
public:
double interest_rate;
SavingsAccount(double balance, double interest):Account(balance)
{
interest_rate = interest;
}
double calculateInterest (){
return (acct_balance * (interest_rate/100));
}
};
class CheckingAccount:public Account{
public:
double charged_fee;
CheckingAccount(double balance, double fee):Account(balance)
{
charged_fee = fee;
}
void credit()
{
acct_balance -= charged_fee;
std::cout << "Checking Account Credit deduction fee "<< Account::acct_balance << std::endl;
}
void debit()
{
if(flagWidraw == true)
acct_balance -= charged_fee;
std::cout << "Checking Account Debit deduction fee "<< acct_balance << std::endl;
}
};
int main()
{
Account a(500.00);
SavingsAccount sa(a.getBalance(),12); //fixed interest rate 12
double interest = sa.calculateInterest();
std::cout << "Interest amount is added to your credit: " << interest << std::endl;
a.credit(interest);
CheckingAccount ca(a.getBalance(), 30);
ca.credit();
std::cout << "Balance is: " << a.getBalance() << std::endl;
return 0;
}
Related
The code does not reduce the default health value, just prints default value out. It does not call GetName() and GetHealth() functions that are inside the TakeDamage() function. The code can run without problem. Screen out put is below the code. Where is the problem here? How do I fix?
#include<iostream>
using namespace std;
class Creature
{
public:
Creature();
void setName(string name);
void TakeDamage(float Damage);
string GetName();
float GetHealth();
private:
string Name;
float Health;
};
class Voldemort : public Creature
{
private:
void AvadaKedavra();
public:
void MakeMagic();
};
void Creature::setName(string name)
{
Name = name;
cout << name << endl;
}
int main()
{
Voldemort Anger;
Anger.MakeMagic();
Anger.setName("Harry Potter");
return 0;
}
Creature::Creature()
{
cout << "A creature has been created" << endl;
Health=100;
}
string Creature::GetName()
{
return Name;
}
float Creature::GetHealth()
{
return Health;
}
void Creature::TakeDamage(float Damage)
{
float Total;
Total = Health - Damage;
if (Total <= 0.f)
{
cout << GetName() << " has died" << endl;
}
else
{
Health -= Damage;
}
cout << "Health: " << Health << endl;
cout << "Health: " << GetHealth() << endl;
}
void Voldemort::MakeMagic()
{
AvadaKedavra();
}
void Voldemort::AvadaKedavra()
{
TakeDamage(100);
}
Screen:
A creature has been created
has died
Health: 100
Health: 100
Harry Potter
if (Total <= 0.f)
{
cout << GetName() << " has died" << endl;
}
else
{
Health -= Damage;
}
You don't change the health when Total is less or equal 0, which is the case when you call TakeDamage(100)
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 am trying to call all the virtual functions in the derived class and then define them outside as the saving class, however I am looks like I am not properly defined my constructor class and I cannot seem to fix it.
I am using the constructor from class accountInfo to store the virtual functions and the protected members and I want balance to update using saving(current_balance,current_interest);. However, I am sure I have a logical error somewhere but I cannot find it. I know I do not use the constructor accountInfo(double addBalance, double intRate); because I want to update the value of balance using the derived class not the parent class
#include <iostream>
#include <math.h>
#include <string>
using namespace std;
class accountInfo{
public:
accountInfo();
accountInfo(double addBalance, double intRate);
virtual void deposit(double amount);
virtual void withdraw(double amount);
virtual double calcInt();
virtual double monthlyProc();
void virtual print();
~accountInfo();
protected:
double balance = 0;
int numDeposits = 0;
int numWithdraws = 0;
double annual_Interest = 0;
double monthlyServiceFee = 10;
bool status = false;
};
class saving: public accountInfo{
public:
saving(double addBalance, double intRate);
void print();
void withdraw(double amount);
void deposit(double amount);
double calcInt();
double monthlyProc();
};
void saving::deposit(double amount){ //how to call back the base function
if(balance >=25){
status = true;
balance +=amount;
numDeposits++;
}
else
status = false;
cout << "Balance is below 25" << endl;
}
accountInfo::accountInfo(){}
accountInfo::accountInfo(double addBalance, double intRate){
balance = addBalance;
annual_Interest = intRate;
}
saving::saving(double addBalance, double intRate){
balance = addBalance;
annual_Interest = intRate;
}
void saving::withdraw(double amount){
balance -= amount;
numWithdraws++;
}
double saving::calcInt(){
double monthlyRate = annual_Interest/12;
double monthlyInterest = balance * monthlyRate;
return balance + monthlyInterest;
}
double saving::monthlyProc(){ //how to call calcInt to delete the following
balance -= monthlyServiceFee;
numWithdraws = 0;
numDeposits = 0;
monthlyServiceFee = 0;
return balance;
}
void saving::print(){
cout <<"current balance " <<balance << endl;
cout << "Interest Rate "<<annual_Interest << endl;
cout << "number of deposits " << numDeposits << endl;
cout << "number of withdraws " << numWithdraws << endl;
cout << "monthlyServiceFee " << monthlyServiceFee << endl;
}
accountInfo::~accountInfo(){}
int main(){
double current_balance = 0;
double current_interest = 0;
double money, money0;
//accountInfo obj0;
accountInfo obj = accountInfo(100,100);
char option;
while(option != 'Q'){
cout << "Select action" << endl;
cin >> option;
option = toupper(option);
saving obj1(current_balance,current_interest);
switch(option){
case('A'):
{
cout << "Please input your balance and interest rate: " << endl;
cin >> current_balance;
cin >> current_interest;
obj1 = saving(current_balance,current_interest);
}
break;
case('D'):
cout << "Money to deposit" << endl;
cin >> money;
obj1.deposit(money);
break;
case('W'):
cout << "Money to withdraw" << endl;
cin >> money0;
obj1.withdraw(money0);
break;
case('P'):
obj1.print();
break;
case ('Q'):
option = 'Q';
break;
}
}
// cout << "the balance after interest is " <<obj.calcInt() << endl;
// cout << "money after the monthly services " << obj.monthlyProc() << endl;
return 0;
}
If you ever have a class:
class Base {
public:
Base();
};
and some other derived class:
class Derived : public Base{
public:
Derived();
};
The proper way to call a parent class' constructor is like this:
Derived::Derived() : Base() {
// Some implementation
}
So you call the constructor after a :. So in your case, it would probably look something like this:
saving::saving(double addBalance, double intRate) : accountInfo(addBalance, intRate) {
// Some implementation
}
This will call accountInfo()'s constructor when saving() is constructed.
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();
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.
`