How to declare a default constructor for subclass? - c++

Very recently, I have started learning C++ full-time.
It is my understanding that constructors in C++ are not inherited by subclasses, and therefore must be declared in the subclass.
Below, I have a program that has a base class Car with a default constructor using default values for the 3 variables, then I have a subclass SportsCar that supposedly invokes the default constructor from the base class.
My problem is that I am having trouble figuring out a way to initialize the new variable acceleration for the subclass constructor to a value such as -2.
Here is my .h file
#include <iostream>
#include <string>
using namespace std;
#ifndef CAR_H_
#define CAR_H_
class Car {
public:
Car();
void SetName(string carName);
void SetMPH(int carMPH);
void SetPrice(double carPrice);
string GetName() const;
int GetMPH() const;
double GetPrice() const;
virtual void display() {
cout << "Car Information: " << endl;
cout << "Model Name: " << name << endl;
cout << "Top Speed: " << mph << " miles per hour" << endl;
cout << "Sales Price: $" << price << endl;
}
void SetInfo(string theName, int theMPH, double thePrice) {
name = theName;
mph = theMPH;
price = thePrice;
}
virtual ~Car() {
cout << "deletion complete" << endl;
}
private:
string name;
int mph;
double price;
};
Car::Car() {
name = "NoName";
mph = -1;
price = 0.0;
}
void Car::SetName(string carName) {
name = carName;
}
void Car::SetMPH(int carMPH) {
mph = carMPH;
}
void Car::SetPrice(double carPrice) {
price = carPrice;
}
string Car::GetName() const {
return name;
}
int Car::GetMPH() const {
return mph;
}
double Car::GetPrice() const {
return price;
}
class SportsCar : public Car {
public:
void SetAcceleration(double carAcceleration) {
acceleration = carAcceleration;
}
double GetAcceleration() const {
return acceleration;
}
void display() override {
Car::display();
cout << "0-60mph Acceleration: " << acceleration << endl;
}
private:
double acceleration;
};
#endif /* CAR_H_ */
Here is my .cpp file:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#include "Car.h"
int main() {
Car* nullCar;
Car* regularCar1;
Car* regularCar2;
SportsCar* nullSportsCar;
vector<Car*> carsList;
unsigned int i;
nullCar = new Car();
carsList.push_back(nullCar);
regularCar1 = new Car();
regularCar1->SetName("2022 Honda Civic");
regularCar1->SetMPH(140);
regularCar1->SetPrice(22550.79);
carsList.push_back(regularCar1);
regularCar2 = new Car();
regularCar2->SetInfo("2022 Nissan Altima", 130, 24900.49);
carsList.push_back(regularCar2);
nullSportsCar = new SportsCar();
carsList.push_back(nullSportsCar);
for (i = 0; i < carsList.size(); i++) {
carsList.at(i)->display();
cout << endl;
}
return 0;
}
Here is the output:
Car Information:
Model Name: NoName
Top Speed: -1 miles per hour
Sales Price: $0
Car Information:
Model Name: 2022 Honda Civic
Top Speed: 140 miles per hour
Sales Price: $22550.8
Car Information:
Model Name: 2022 Nissan Altima
Top Speed: 130 miles per hour
Sales Price: $24900.5
Car Information:
Model Name: NoName
Top Speed: -1 miles per hour
Sales Price: $0
0-60mph Acceleration: 0
It works fine, but I want the last output "0-60mph Acceleration" to read -2 instead of 0. I just don't know how to declare a default constructor for the subclass to do that.

Do you mean:
class SportsCar : public Car {
public:
SportsCar()
: Car() // Parent Init
// Preferrer using initializer list for members
// After Parents come members
, acceleration(-2)
{}
....
};

Related

How to reuse variables from the base class to the derived class

I am working on a project to show statistics for a generic vehicle, then for a car and a truck.
All of the objects have a Manufacturer and Model Year, but the Car has a number of doors, and the truck has a towing capacity.
I have my vehicle class and class constructors all working properly in the code.
Now I want to call the same method of data storage from the base class Vehicle, and use it for the Car Class.
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Vehicle {
private:
string manu;
int year;
public:
// Default constructor
Vehicle() {
manu = "";
year = 0;
}
// Constructor
Vehicle(string autoManu, int autoYear) {
manu = autoManu;
year = autoYear;
}
// Accessors
string getManu() const { return manu; }
int getModel() const { return year; }
void storeInfo(string autoManu, int autoYear);
void displayInfo();
};
This is my Vehicle.h file ^
#include "Vehicle.h"
void Vehicle::storeInfo(string autoManu, int autoYear) {
manu = autoManu;
year = autoYear;
}
void Vehicle::displayInfo() {
cout << "Manufacturer- " << manu << endl;
cout << "Make Year- " << year << endl;
}
This is my Vehicle.cpp file ^
These both work perfectly, now I want to use the same kind of displayInfo for the Car class.
#pragma once
#include <iostream>
#include "Vehicle.h"
#include <string>
using namespace std;
// The Car class represents a car.
class Car : public Vehicle {
private:
int doors;
public:
// Default constructor
Car() : Vehicle() { doors = 0; }
// Constructor #2
Car(string carManu, int carYear, int carDoors) : Vehicle(carManu, carYear) {
doors = carDoors;
}
// Accessor for doors attribute
int getDoors() { return doors; }
void storeInfo(string autoManu, int autoYear, int carDoors);
void displayInfo();
};
This is my Car.h file ^
#include "Car.h"
void Car::storeInfo(string autoManu, int autoYear, int carDoors) {
manu = autoManu;
year = autoYear;
doors = carDoors;
}
void Car::displayInfo() {
cout << "Manufacturer- " << manu << endl;
cout << "Make Year- " << year << endl;
cout << "Doors on the Car" << doors << endl;
}
This is the Car.cpp file.
The issue I am encountering is that the menu and year variables, the variables defined in the base class, are saying "Vehicle::manu is inaccessible"
What would be causing this, and what is the fix?
Thanks!

base class initialization error, no matching constructor

First and foremost I'd like to apologize for the magnitude of code I'm dumping. I'm writing some code that allows the user to withdraw and deposit money into an account, the code also calculates the interest rate of the account and the number of withdrawals and deposits etc. I get on error when I try to call the base class functions to the child functions, "no matching constructor." I can't seem to find a problem with the constructors on my own. Can anyone help?
Account.cpp
#include "Account.h"
#include <iostream>
#include <iomanip>
using namespace std;
//overloaded constructor
Account::Account(double accBal, double annIntRate){
accBal = accBal;
annIntRate = annIntRate;
};
//deposit base class function
int Account::deposit(double accBal, int numWithdrawal)
{
cout << "Enter deposit: "<< endl;
double depos;
cin >> depos;
accBal += depos;
numDepos ++;
return accBal;
}
//withdraw base class function
void Account::withdraw(double accBal, int numWithdrawal)
{
double amount;
cin >> amount;
accBal -= amount;
numWithdrawal ++;
}
//interest rate calculation
void Account::calcInt(double accBal, double annIntRate)
{
double monthlyIntRate = annIntRate/2;
double monthlyInt = accBal * monthlyIntRate;
accBal += monthlyInt;
}
Account.h
#ifndef ACCOUNT_H
#define ACCOUNT_H
class Account
{
//variable declarations
private:
int accNum;
double accBal;
int numWithdrawal;
int numDepos;
double annIntRate;
double monthServCharg;
public:
Account(double, double); //overloaded constructor
virtual int deposit(double, int); //base class deposit declaration
virtual void withdraw(double, int); //base class withdraw declaration
virtual void calcInt(double, double); //updates interest rate
void setAccNum(int); //setter
int getAccNum(){return accNum;} //getter
void setAccBal(double);//setter
double getAccBal(){return accBal;}//getter
void setNumWithdrawal(int);//setter
int getNumWithdrawal(){return numWithdrawal;}//getter
void setNumDep(int);//setter
int getNumDep(){return numDepos;}//getter
void setAnnIntRate(double);//setter
double getAnnIntRate(){return annIntRate;}//getter
void setMonthServCharg(double); //setter
double getMonthServCharg(){return monthServCharg;}//getter
};
#endif
SavingsAccount.cpp
#include "SavingsAcc.h"
#include "Account.h"
#include <iostream>
using namespace std;
//status constructor
SavingsAccount::SavingsAccount(bool status)
{
status = false;
}
//deposit money function
void SavingsAccount::deposit(bool status, double accBal, int numDepos)
{
Account obj;
obj.deposit(accBal); //PROBLEM
if (accBal > 25.00)
status = true;
else
status = false;
}
//withdraw money child function, updates account status, service charges, interest rate etc
void SavingsAccount::withdraw(double accBal, int numWithdrawal, double annIntRate, double monthServCharg)
{
double amount;
if (accBal <= 25.00)
cout << "Balance too low, withdrawals cannot be made at this time"<<endl;
else
{
do
{
Account obj;
obj.withdraw(numWithdrawal); // PROBLEM
if (numWithdrawal > 4)
monthServCharg += 1;
if (accBal < 25.00)
{annIntRate += 0.01;}
}
while (amount > accBal);
cout << "Insufficient funds!";
}
}
//outputs the report of account
void SavingsAccount::accountReport(int accNum, bool status, int numWithdrawal, int numDepos, double monthServeCharg, double accBal)
{
cout << "====ACCOUNT STATUS===="<<endl;
cout << "Account number: "<< accNum <<endl;
if (status == true) //status
cout << "Satus: Active" << endl;
else
cout <<"Status: Inactive" << endl;
cout << "Total deposits: "<< numDepos << endl;
cout << "Total withdrawals" << numWithdrawal << endl;
cout << "Service charges: "<< monthServeCharg << endl;
cout << "Balance: "<<accBal<<endl;
}
SavingsAccount.h
#ifndef SAVINGSACC_H
#define SAVINGSACC_H
#include <iostream>
class SavingsAccount: public Account
{
private:
bool status; //status variable
public:
SavingsAccount(bool); // constuctor
void deposit(bool, double, int); // deposit function
void withdraw(double, int, double, double); //withdraw function
void accountReport(int, bool, int, int, double, double ); // full report of account
};
#endif
The constructor
Account(double, double); //overloaded constructor
is actually not overloading constructor but invalidating the default constructor.
To use this constructor, passing values for the arguments when constructing SavingsAccount like
SavingsAccount::SavingsAccount(bool status) : Account(42, 334)
{
status = false;
}
is required.
Also the line
obj.deposit(accBal); //PROBLEM
is causing error because the class Account doesn't have function deposit that takes only one argument. You should delete the line or pass right number of arguments to resolve this error.

C++ questions on Inheritance, privacy, and objects in a shipping program with multiple classes and headers

My program is supposed to print a "to" and "from" address sourced from the EndPoint toString method but I can't quite figure out how to implement it. Here is my code. How do I get the toString method in the Package::Package constructor to print the contents of the EndPoint's toString method?
// ShippingProgram.cpp :
//
#include "stdafx.h"
#include <iomanip>
#include <stdexcept>
#include <sstream>
#include <iostream>
#include "Package.h" // Package class definition
using namespace std;
// constructor
EndPoint::EndPoint(const string& nameInfo, const string& addressInfo, const string& cityInfo, const string& stateInfo, int zipInfo) {
name = nameInfo;
address = addressInfo;
city = cityInfo;
state = stateInfo;
zip = zipInfo;
}
string EndPoint::toString() const {
ostringstream output;
output << fixed << setprecision(2); // two digits of precision
output << name << "\n" << address << "\n" <<
city << ", " << state << " " << zip;
return output.str();
}
Package::Package(EndPoint senderInfo, EndPoint receiverInfo, double weightInfo, double costPerOzInfo) {
weight = weightInfo; // should validate
costPerOz = costPerOzInfo;
}
void Package::calculateCost(double)
{
}
double Package::calculateCost() const {
return weight * costPerOz;
}
string Package::toString() const {
ostringstream output;
output << fixed << setprecision(2); // two digits of precision
output << "\nFrom:\n" << senderInfo.toString() << "\n\nTo:\n" << receiver <<
"\n\nWeight: " << weight << endl <<
"\nShipping cost:\n" << calculateCost();
return output.str();
}
Main Method:
#include <iostream>
#include <iomanip>
#include "stdafx.h"
//#include "TwoDayPackage.h"
//#include "OvernightPackage.h"
#include "Package.h"
using namespace std;
int main()
{
// Three address records.
EndPoint homer{ "Homer Simpson", "742 Evergreen Terrace", "Springfield",
"FL", 32401 };
EndPoint donald{ "Donald Duck", "1313 Webfoot Walk", "Duckburg",
"CA", 95501};
EndPoint kermit{ "Kermit Frog", "On the Swamp", "Leland", "MS", 38756 };
// This calls the base class constructor (regular fee).
Package regular{ homer, donald, 25.0, 0.20 };
// Defines output precision for floating point numbers (iomanip).
// cout << fixed << setprecision(2);
// Prints package parameters.
cout << "Regular package processed." << endl;
cout << regular.toString();
cout << "Shipping Cost: $" << regular.calculateCost() << endl << endl;
cout << homer.toString();
// First derived class (two-day fee added).
/* TwoDayPackage twoday{ donald, kermit, 17.5, 0.20, 2.0 };
cout << "Two-day package processed." << endl;
cout << twoday.toString();
cout << "Shipping Cost: $" << twoday.calculateCost() << endl << endl;
// Second derived class (overnight fee added).
OvernightPackage overnight{ kermit, homer, 14.2, 0.20, 0.50 };
cout << "Overnight package processed." << endl;
cout << overnight.toString();
cout << "Shipping Cost: $" << overnight.calculateCost() << endl << endl;
*/
}
This project requires that I create a shipping program with inheritance. It must include a "EndPoint" class that is private and contains the sender and receiver info and a "Package" class that compiles everything and puts it to string.
My Errors are with how in the world I get my Package constructor to be able to contain the information from my EndPoint class. Since the main method is formatted where the Package class must be (EndPoint, EndPoint, Weight, Cost) but it doesn't compile like that. I guess I just don't understand how to send the EndPoint info to the Package objects.
Here are my errors:
No instance of constructor "Package::Package" matches the argument list argument types are: (EndPoint, EndPoint, double, double)
Error C2440 'initializing': cannot convert from 'initializer list' to 'Package'
Error C3861 'setprecision': identifier not found
Package.h
#pragma once
#ifndef PACKAGE_H
#define PACKAGE_H
#include <string>
#include <iostream>
using namespace std;
class EndPoint {
public:
EndPoint(const std::string&, const std::string&, const std::string&, const std::string&, int = 0.0);
void setName(const std::string&);
std::string getName() const;
void setAddress(const std::string&);
std::string getAddresss() const;
void setCity(const std::string&);
std::string getCity() const;
void setState(const std::string&);
std::string getState() const;
void setZip(int);
int getZip() const;
string toString() const;
protected:
std::string name;
std::string address;
std::string city;
std::string state;
int zip;
};
class Package {
public:
string toString() const;
Package(const std::string&, const std::string&, double = 0.0, double = 0.0);
void setSender(const std::string&);
std::string getSender() const;
void setReceiver(const std::string&);
std::string getReceiver() const;
void setWeight(double);
double getWeight() const;
void setCostPerOz(double);
double getCostPerOz() const;
void calculateCost(double);
double calculateCost() const;
double calculateCost(double weight, double costPerOz)
{
double shipping;
shipping = weight * costPerOz;
cout << "The Base Cost = " << shipping << endl << endl;
return shipping;
}
protected:
std::string sender;
std::string receiver;
double weight; // gross weekly sales
double costPerOz; // commission percentage
};
#endif
Package.cpp
#include "stdafx.h"
#include <iomanip>
#include <stdexcept>
#include <sstream>
#include "Package.h" // Package class definition
using namespace std;
// constructor
EndPoint::EndPoint(const string& nameInfo, const string& addressInfo, const string& cityInfo, const string& stateInfo, int zipInfo) {
name = nameInfo;
address = addressInfo;
city = cityInfo;
state = stateInfo;
zip = zipInfo;
}
void EndPoint::setName(const string& nameInfo) {
name = nameInfo;
}
string EndPoint::getName() const { return name; }
void EndPoint::setAddress(const string& addressInfo) {
address = addressInfo;
}
string EndPoint::getAddresss() const { return address; }
void EndPoint::setCity(const string& cityInfo) {
city = cityInfo;
}
string EndPoint::getCity() const { return city; }
void EndPoint::setState(const string& stateInfo) {
state = stateInfo;
}
string EndPoint::getState() const { return state; }
void EndPoint::setZip(int zipInfo) {
zip = zipInfo;
}
int EndPoint::getZip() const {
return zip;
}
string EndPoint::toString() const {
ostringstream output;
output << fixed << setprecision(2); // two digits of precision
output << name << "\n" << address << "\n" <<
city << ", " << state << " " << zip;
return output.str();
}
string EndPoint::getState() const { return state; }
Package::Package(const string& senderInfo, const string& receiverInfo, double weightInfo, double costPerOzInfo) {
sender = senderInfo; // should validate
receiver = receiverInfo; // should validate
weight = weightInfo; // should validate
costPerOz = costPerOzInfo;
}
void Package::setSender(const string& senderInfo) {
sender = senderInfo; // should validate
}
string Package::getSender() const { return sender; }
void Package::setReceiver(const string& receiverInfo) {
receiver = receiverInfo; // should validate
}
string Package::getReceiver() const { return receiver; }
void Package::setWeight(double weightInfo) {
if (weightInfo < 0.0) {
throw invalid_argument("The package weight must be >= 0.0");
}
weight = weightInfo;
}
double Package::getWeight() const { return weight; }
void Package::setCostPerOz(double costPerOzInfo) {
costPerOz = costPerOzInfo;
}
double Package::getCostPerOz() const {
return costPerOz;
}
double Package::calculateCost() const {
return weight * costPerOz;
}
string Package::toString() const {
ostringstream output;
output << fixed << setprecision(2); // two digits of precision
output << "From:\n" << sender << "\n\nTo:\n" << receiver <<
"\n\nWeight: " << weight << endl <<
"\nShipping cost: " << calculateCost();
return output.str();
}
Main.cpp
#include <iostream>
#include <iomanip>
#include "stdafx.h"
//#include "TwoDayPackage.h"
//#include "OvernightPackage.h"
#include "Package.h"
using namespace std;
int main()
{
// Three address records.
EndPoint homer{ "Homer Simpson", "742 Evergreen Terrace", "Springfield",
"FL", 32401 };
EndPoint donald{ "Donald Duck", "1313 Webfoot Walk", "Duckburg",
"CA", 95501};
EndPoint kermit{ "Kermit Frog", "On the Swamp", "Leland", "MS", 38756 };
// This calls the base class constructor (regular fee).
Package regular{ homer, donald, 25.0, 0.20 };
// Defines output precision for floating point numbers (iomanip).
cout << fixed << setprecision(2);
// Prints package parameters.
cout << "Regular package processed." << endl;
cout << regular.toString();
cout << "Shipping Cost: $" << regular.calculateCost() << endl << endl;
// First derived class (two-day fee added).
/* TwoDayPackage twoday{ donald, kermit, 17.5, 0.20, 2.0 };
cout << "Two-day package processed." << endl;
cout << twoday.toString();
cout << "Shipping Cost: $" << twoday.calculateCost() << endl << endl;
// Second derived class (overnight fee added).
OvernightPackage overnight{ kermit, homer, 14.2, 0.20, 0.50 };
cout << "Overnight package processed." << endl;
cout << overnight.toString();
cout << "Shipping Cost: $" << overnight.calculateCost() << endl << endl;
*/
}
I have commented out blocks of code here as I am trying to just get the first part to work before diving into the rest.
Edit:
Thank you all for the advice! I have made some edits and taken out a ton of extra code (getters and setter. I learned with java...) and I have gotten the program to compile and work as intended save for a small but important issue.
No instance of constructor "Package::Package" matches the argument
list argument types are: (EndPoint, EndPoint, double, double)
in your code:
Package regular{ homer, donald, 25.0, 0.20 }; you are passing wrong variables to the constructor's parameters which is an Endpoint object for first and second parameter
what you have is:
Package(const std::string&, const std::string&, double = 0.0, double = 0.0);
which accepts a std::string object for first and second parameter.
cannot convert from 'initializer list' to 'Package
fixing problem 1 will fix this
i dont know why you get 3rd one since you have iomanip in your main

Undefined Reference c++ lost

#include "assert.h"; // for some reason assert wouldn't work on my compiler without this
#include <iostream>
#include <string>
#include <limits> // This is helpful for inputting values. Otherwise, funny stuff happens
using namespace std;
class Product
{
public:
Product();
Product(string the_name, int the_price, int number_of);
string return_name();
void reduce_amount();
void print_data() const;
private:
string prod_name; // name of your product
int price_in_cents; // it's price in cents
int amount; // the number of the product that you have
};
Product::Product()
{
prod_name = "NULL_NAME: NEED DATA";
price_in_cents = 0;
}
Product::Product(string the_name, int the_price, int number_of)
{
assert(the_price>0);
assert(number_of>0);
assert(number_of<21);
assert(prod_name !="NULL_NAME: NEED DATA");
prod_name = the_name;
price_in_cents = the_price;
amount = number_of;
}
void Product::print_data() const
{
cout<<prod_name << endl;
cout<<"The price in cents is: " <<price_in_cents<< endl;
cout<< "Amount left: " << " " << amount << endl;
}
void Product::reduce_amount()
{
amount = amount -1;
}
string Product::return_name()
{
return prod_name;
}
class Vending_Machine
{
public:
Vending_Machine();
void empty_coins();
void print_vend_stats();
void add_product();
Product buy_product();
private:
int income_in_cents;
Product product1();
Product product2();
Product product3();
Product product4();
Product product5();
};
void Vending_Machine::empty_coins()
{
cout << "The total amount of money earned today is " << income_in_cents << " cents" << endl;
income_in_cents = 0;
cout << "All the coins have been withdrawn. The balance is now zero." << endl;
}
void Vending_Machine::print_vend_stats()
{
cout<< "Total income thus far: " << income_in_cents << endl;
if (product1().return_name() != "NULL_NAME: NEED DATA")
{
//stuff happens
}
}
int main()
{
return 0;
}
So, I'm not sure if I did all the identation correctly, but I'm having a problem with the boolean statement in vending machine print_vend_stats() function. It's saying I am making an undefined fereence to product1(). What does this mean?
When you declare
Product product1();
you declare a member function, the parentheses is what makes it a function.
If you drop the parentheses
Product product1;
you declare a member variable, an actual instance of the Product class.
Another example, you wouldn't write e.g.
int income_in_cents();
do declare income_in_cents as a variable, now would you?
It doesn't matter if the type is a primitive type like int, or a class like Product, Member variables are declared like normal variables like you do anywhere else.

Whats wrong with my class [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I don't know why but when i create an object with my class and use the default constructor, when i try to pass the variable named cash to the accessor user2.setCash(cash) which purpose is to primary set cash equal to new_cash, it gives a large value like 1.222256e+461 or something like that. Why does that happen? If i use my overload constructor it works fine.
main.cpp
#include <iostream>
#include <string>
#include "Bank.h"
using namespace std;
int main()
{
string name;
int id;
double cash;
bank user2;
cout << "\n\nPlease type your name: ";
getline(cin >> ws, name);
user2.setName(name);
cout << "Enter an id number: ";
cin >> id;
user2.setID(id);
cout << "Enter your cash: ";
cin >> cash;
cout << cash << endl;
user2.setCash(cash);
cout << "\nAlright " << user2.getName() << ", current cash: " << user2.getCash();
cout << "\nChoose how much would you like to Deposit: ";
cin >> cash;
user2.deposit(cash);
cout << "New amount is: " << user2.getCash() << " For user ID: " << user2.getID() << "\n\n";
bank::printStatic();
return 0;
}
Bank.h
#ifndef BANK_H
#define BANK_H
#include <iostream>
#include <string>
using namespace std;
class bank
{
public:
// Default Constructor
bank();
// Overload Constructor
bank(string, int, double);
// Destructor
~bank();
// Accessor Functions
string getName() const;
int getID() const;
double getCash() const;
// Mutator Functions
void setName(string);
void setID(int);
void setCash(double);
// Functions
void withdraw(double);
void deposit(double);
static void printStatic();
private:
// Member Variables
string new_name;
int new_id;
double new_cash;
// Static Member Variables
static int num_of_accounts;
static double total_cash;
};
#endif
Bank.cpp
#include "Bank.h"
// Static Variables
int bank::num_of_accounts = 0;
double bank::total_cash = 0.0;
// Default Constructor
bank::bank()
{
int new_id = 0;
double new_cash = 0.0;
++num_of_accounts; // New object is created e.g. a person so total accounts must be increased.
}
// Overload Constructor
bank::bank(string name, int id, double cash)
{
new_name = name;
new_id = id;
new_cash = cash;
++num_of_accounts; // New object is created e.g. a person so total accounts must be increased.
total_cash += new_cash; // New object is created e.g. a person so his/hers cash must be added to the total cash of the bank.
}
// Destructor
bank::~bank()
{
--num_of_accounts; // When Destructor is called to destroy an object (e.g. a person) then the id must be dropped by 1 cause the person e.g. (left).
total_cash -= new_cash; // And the balance he had to be removed so it is not counted in total cash avaliable in the bank cause he e.g. (left).
}
// Accessor Functions
string bank::getName() const
{
return new_name;
}
int bank::getID() const
{
return new_id;
}
double bank::getCash() const
{
return new_cash;
}
// Mutator Functions
void bank::setName(string name)
{
new_name = name;
}
void bank::setID(int id)
{
new_id = id;
}
void bank::setCash(double cash)
{
cout << new_cash << endl;
total_cash -= new_cash; // We must remove his prior cash which we holded in the total so we can then use the new value suplied.
new_cash = cash;
total_cash += new_cash; // Here we add the new cash (balance) he/she has.
}
void bank::withdraw(double cash)
{
new_cash -= cash;
total_cash -= cash;
}
void bank::deposit(double cash)
{
new_cash += cash;
total_cash += cash;
}
void bank::printStatic()
{
cout << "Total users are: " << num_of_accounts << endl;
cout << "Total cash in bank is: " << total_cash << endl;
}
You need to initialize all primitive type members in the constructor.
Otherwise you get indeterminate values
Also, the non-default constructor is buggy:
// Default Constructor
bank::bank()
{
int new_id = 0;
double new_cash = 0.0;
....
^ sets values of local variables, not the member variables
I'd suggest to use the initilization lists:
// Default Constructor
bank::bank() : new_name(), new_id(0), new_cash(0.0)
{
++num_of_accounts;
}
// Overload Constructor
bank::bank(string name, int id, double cash)
: new_name(name), new_id(id), new_cash(cash)
{
++num_of_accounts;
total_cash += new_cash;
}
You could also combine the two:
bank::bank(string name = "", int id = 0, double cash = 0.0)
: new_name(name), new_id(id), new_cash(cash)
{
++num_of_accounts;
total_cash += new_cash;
}
In your default constructor, you're declaring local variables with the same names as the member variables. Then you're setting these local variables instead of assigning the members. Get rid of the type declarations so they're normal assignments.
bank::bank()
{
new_id = 0;
new_cash = 0.0;
++num_of_accounts; // New object is created e.g. a person so total accounts must be increased.
}