Cannot instantiate abstract class, but double checked overriding of virtual functions - c++

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));

Related

Why do I get the error "use of deleted function 'class : : class()"

#include <iostream>
using namespace std;
class student
{
protected:
string name;
int roll;
int age;
public:
student(string n, int r, int a)
{
name = n;
roll = r;
age = a;
}
};
class test : public student
{
protected:
int sub[5];
public:
void marks()
{
cout << "Enter marks in 5 subjects: " << endl;
cin >> sub[0] >> sub[1] >> sub[2] >> sub[3] >> sub[4];
}
void display()
{
cout << "Name : " << name << "\nRoll number : " << roll << "\nAge: " << age << endl;
cout << "Marks in 5 subjects : " << sub[0] << ", " << sub[1] << ", " << sub[2] << ", " << sub[3] << ", " << sub[4] << endl;
}
};
class sports
{
protected:
int sportmarks;
public:
sports(int sm)
{
sportmarks = sm;
}
};
class result : public test, public sports
{
int tot;
float perc;
public:
void calc()
{
tot = sportmarks;
for(int i = 0; i < 5; i++)
tot = tot + sub[i];
perc = (tot / 600.0) * 100;
cout << "Total: " << tot << "\nPercentage: " << perc << endl;
}
};
int main()
{
student ob1("Name", 781, 19);
sports ob2(78);
result ob;
ob.marks();
ob.display();
ob.calc();
}
I've been asked to use parameterized constructors to do this problem and notice I get these errors when I use constructors. Sorry if this post is inconvenient to read. In what way can I run this code while creating objects from parameterized constructors?
use of deleted function 'result::result()'
use of deleted function 'test::test()'.
no matching function for call to 'student::student()'
no matching function for call to 'sports::sports()'
student and sports have user-defined constructors, so the compiler does not generate default constructors for them.
test and result have no user-defined constructors, so the compiler will generate default constructors for them. However, since student and sports have no default constructors, the generated default constructors are marked delete'd as they are not usable. That is why you get errors.
To make your main() compile as-is, you need to define your own default constructors for test and result which pass explicit parameter values to their base classes, eg:
#include <iostream>
using namespace std;
class student
{
protected:
string name;
int roll;
int age;
public:
student(string n, int r, int a)
{
name = n;
roll = r;
age = a;
}
};
class test : public student
{
protected:
int sub[5];
public:
test() : student("", 0, 0) {}
void marks()
{
cout << "Enter marks in 5 subjects: " << endl;
cin >> sub[0] >> sub[1] >> sub[2] >> sub[3] >> sub[4];
}
void display()
{
cout << "Name : " << name << "\nRoll number : " << roll << "\nAge: " << age << endl;
cout << "Marks in 5 subjects : " << sub[0] << ", " << sub[1] << ", " << sub[2] << ", " << sub[3] << ", " << sub[4] << endl;
}
};
class sports
{
protected:
int sportmarks;
public:
sports(int sm)
{
sportmarks = sm;
}
};
class result : public test, public sports
{
int tot;
float perc;
public:
result() : test(), sports(0) {}
void calc()
{
tot = sportmarks;
for(int i = 0; i < 5; i++)
tot = tot + sub[i];
perc = (tot / 600.0) * 100;
cout << "Total: " << tot << "\nPercentage: " << perc << endl;
}
};
int main()
{
student ob1("Name", 781, 19);
sports ob2(78);
result ob;
ob.marks();
ob.display();
ob.calc();
}
Online Demo
However, this is not very useful, so I would suggest tweaking result's constructor to take the student and sports objects you have already created beforehand, and pass them to the base class copy constructors, which the compiler will generate for you, eg:
#include <iostream>
using namespace std;
class student
{
protected:
string name;
int roll;
int age;
public:
student(string n, int r, int a)
{
name = n;
roll = r;
age = a;
}
};
class test : public student
{
protected:
int sub[5];
public:
test(const student &s) : student(s) {}
void marks()
{
cout << "Enter marks in 5 subjects: " << endl;
cin >> sub[0] >> sub[1] >> sub[2] >> sub[3] >> sub[4];
}
void display()
{
cout << "Name : " << name << "\nRoll number : " << roll << "\nAge: " << age << endl;
cout << "Marks in 5 subjects : " << sub[0] << ", " << sub[1] << ", " << sub[2] << ", " << sub[3] << ", " << sub[4] << endl;
}
};
class sports
{
protected:
int sportmarks;
public:
sports(int sm)
{
sportmarks = sm;
}
};
class result : public test, public sports
{
int tot;
float perc;
public:
result(const student &s, const sports &sp) : test(s), sports(sp) {}
void calc()
{
tot = sportmarks;
for(int i = 0; i < 5; i++)
tot = tot + sub[i];
perc = (tot / 600.0) * 100;
cout << "Total: " << tot << "\nPercentage: " << perc << endl;
}
};
int main()
{
student ob1("Name", 781, 19);
sports ob2(78);
result ob(ob1, ob2);
ob.marks();
ob.display();
ob.calc();
}
Online Demo

Is it possible to create a constructor for a derived class?

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.

Trouble while compiling code - strncpy char* and string

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/

cannot change the value of base class variable from derived class

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;
}

C++ Operator Overloading always false

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();