C++ chain inheritance - c++

Im trying to create a percent savings program for a supermarket with 3 inherited classes (PersonData -> CustomerData -> PreferredCustomer). The entire program has to follow this UML diagram:
I am having problems with the third class; specifically initializing values in the first constructor of the class. Im getting an error message in visual studio: "redefinition of formal parameter Pa" and "redefinition of formal parameter "dl".
This is the constructor with the errors:
PreferredCustomer(string aLname, string aFname, string aAddress,
string aCity, string aState, int aZip, string aPhone, int cn,
bool ml, double Pa, double dl) // constructor 1
{
double Pa;
double dl;
}
The parameters in this third child constructor have been overloaded from the parent constructor. Arguments cn, ml, Pa, dl have all been added into this parameter.
I'm not sure why i am getting these errors? Also, should i be creating a virtual function or using pointers? Thank you for any help.
My program source code (for reference):
#include <iostream>
#include <string>
using namespace std;
class PersonData // PersonData parent class defined
{
private:
string lastName;
string firstName;
string address;
string city;
string state;
string phone;
int zip;
public:
PersonData() // Default Constructor initialization
{
lastName = " ";
firstName = " ";
address = " ";
city = " ";
state = " ";
zip = 0;
phone = " ";
}
PersonData(string aLname, string aFname, string aAddress, string aCity, string aState, int aZip, string aPhone) // Constructor 1
{
lastName = aLname;
firstName = aFname;
address = aAddress;
city = aCity;
state = aState;
zip = aZip;
phone = aPhone;
}
// Accesor Functions
string getLastName() const
{
return lastName;
}
string getFirstName() const
{
return firstName;
}
string getAddress() const
{
return address;
}
string getCity() const
{
return city;
}
string getState() const
{
return state;
}
int getZip() const
{
return zip;
}
string getPhone() const
{
return phone;
}
// Mutator Functions
void setLastName(string aLname)
{
lastName = aLname;
}
void setFirstName(string aFname)
{
firstName = aFname;
}
void setAddress(string aAddress)
{
address = aAddress;
}
void setCity(string aCity)
{
city = aCity;
}
void setState(string aState)
{
state = aState;
}
void setZip(int aZip)
{
zip = aZip;
}
void setPhone(string aPhone)
{
phone = aPhone;
}
};
class CustomerData :public PersonData // CustomerData child class of PersonData base class
{
private:
int customerNumber;
bool mailingList;
public:
CustomerData() // Default constructor
{
customerNumber = 0;
mailingList = 0;
}
CustomerData(int cNum, bool mailL) // Constructor 1
{
setCustomerNumber(cNum);
setMailingList(mailL);
}
// Accessor Functions for child class
int getCustomerNumber() const
{
return customerNumber;
}
bool getMailingList() const
{
if (mailingList != 0)
{
cout << "On Mailing List!: ";
return mailingList;
}
else (mailingList == 0);
{
cout << "Not on mailing list!: ";
return mailingList;
}
}
// Mutator Functions for child class
void setCustomerNumber(int cNum)
{
customerNumber = cNum;
}
void setMailingList(bool mailL)
{
mailingList = mailL;
}
};
class PreferredCustomer :public CustomerData // child class of CustomerData child class
{
private:
double purchasesAmount;
double discountLevel;
public:
PreferredCustomer() // default constructor
{
purchasesAmount = 0;
discountLevel = 0;
}
PreferredCustomer(string aLname, string aFname, string aAddress,
string aCity, string aState, int aZip, string aPhone, int cn,
bool ml, double Pa, double dl) // constructor 1
{
double Pa;
double dl;
}
// Mutator Functions
void setPurchasesAmount(double Pa)
{
purchasesAmount = Pa;
}
// Accessor Functions
double getPurchasesAmount() const
{
return purchasesAmount;
}
double getDiscountLevel() const
{
return discountLevel;
}
void addPurchase(double P) const
{
}
};
int main()
{
CustomerData Cdata; // for access of child class functions
PersonData Pdata; // for access of parent class functions
PreferredCustomer PCdata; // for access of preferred customer class functions
string temp1; // Temporary variable for string values
int temp2, // Temporary variable for integer values
max = 100, // For-loop maximum loop value
i; // i variable
bool temp3; // Temporary variable for bool values
for (i = 1; i <= max; i++)
{
// Input Data
cout << "Please input first Name: ";
getline(cin, temp1);
Pdata.setFirstName(temp1);
cout << "Please input last Name: ";
getline(cin, temp1);
Pdata.setLastName(temp1);
cout << "Please input address: ";
getline(cin, temp1);
Pdata.setAddress(temp1);
cout << "Please input city: ";
getline(cin, temp1);
Pdata.setCity(temp1);
cout << "Please input state: ";
getline(cin, temp1);
Pdata.setState(temp1);
cout << "Please input Zip code: ";
cin >> temp2;
Pdata.setZip(temp2);
cin.ignore(); // discards unread char from cin
cout << "Please input Phone Number: ";
getline(cin, temp1);
Pdata.setPhone(temp1);
cout << "Enter 1 to be included in mail list," << endl;
cout << "Enter 0 to not be included in mail list: ";
cin >> temp3;
Cdata.setMailingList(temp3);
Cdata.setCustomerNumber(i); // set customer number
cout << endl << endl;
cout << "Name: " << Pdata.getFirstName() << ", " << Pdata.getLastName() << " \n";
cout << "Customer Number: " << Cdata.getCustomerNumber() << "\n";
cout << "Address: " << Pdata.getAddress() << "\n";
cout << "City: " << Pdata.getCity() << "\n";
cout << "State: " << Pdata.getState() << "\n";
cout << "Phone: " << Pdata.getPhone() << "\n";
cout << "Zip: " << Pdata.getZip() << "\n";
cout << Cdata.getMailingList() << "\n";
cout << endl << endl;
cin.ignore(); // discards unread char from cin
}
char c;
cin >> c;
return 0;
}

A constructor's purpose is to take the parameters the are passed in and construct the object from the class declaration and initialize members as appropriate. It not only has to initialize the class but also all the base classes as well, this can be done by passing parameters to the base constructor(s).
In
PreferredCustomer(string aLname, string aFname, string aAddress,
string aCity, string aState, int aZip, string aPhone, int cn,
bool ml, double Pa, double dl) // constructor 1
{
double Pa;
double dl;
}
You aren't initializing anything
You are declaring two local parameters that match (and conflict with) the parameters passed in
You don't call the base's constructors (how most of the work is done)
PreferredCustomer(...) :CustomerData(...)
CustomerData(...) :PersonData(...)
You don't initialize this class's members
purchasesAmount = pa;
discountLevel = dl;

Related

Overriding Print Function not over riding base class

I am trying to get my code to display the Ship class data, then use pointers to display the updated data after enter in console and set to the relevant variables in the CruiseShip and CragoShip classes. However, the program will ignore any new input and simply display the base class data again regardless of new data.
What is missing here?
using namespace std;
// -- Initialized the class 'Ship' -- //
class Ship {
public:
int yearBuilt;
string nameOfShip;
// Constructs the ship class and defines the values of the variables
Ship() {
yearBuilt = 0;
nameOfShip = "";
}
// Overloaded Constructor
Ship(int year, string name) {
Ship::yearBuilt = year;
Ship::nameOfShip = name;
year = 0;
name = "";
}
// Accessor Function for the year the ship was built
int getYearBuilt() const {
return yearBuilt;
}
// Accessor Function for the name of the ship
string getShipName() const {
return nameOfShip;
}
// Mutator Function to read input and set it to the value of yearBuilt
void setShipYear(int year) {
cout << " Enter Year: " << endl;
cin >> year;
year = yearBuilt;
cout << endl; // Spacing between printed data
}
// Mutator Function to read input and set it to the value of nameOfShip
void setShipName(string name) {
cout << " Enter Name: " << endl;
cin >> name;
name = nameOfShip;
cout << endl; // Spacing between printed data
}
// Virtual Print function to display the name of the ship and the year it was built
virtual void print() const {
cout << " Ship Name: " << nameOfShip << endl;
cout << " Year Built: " << yearBuilt << endl;
}
};
// -- Initializes the class 'CruiseShip' derived from Ship class -- //
class CruiseShip : public Ship
{
// Set the member variable for max number of passengers
int passengersMAX;
public:
//Constructor for CruiseShip, calls parent class
CruiseShip() : Ship() {
passengersMAX = 0;
}
//Overloaded Constructor
CruiseShip(int maximum, int year, string name) : Ship() {
CruiseShip::passengersMAX = maximum;
}
//Accessor
int getMaxPass() const {
return passengersMAX;
}
//Mutator
void setMaxPass(int maximum) {
cout << "Enter Passenger Max: " << endl;
cin >> maximum;
maximum = passengersMAX;
}
//Overriding Print Function
virtual void print() const override{
cout << " Ship Name: " << nameOfShip << endl;
cout << " Max number Of Passengers: " << passengersMAX << endl;
}
};
class CargoShip : public Ship
{
// Set the member variable for tonnage / capacity
int capacity;
public:
// Default Constructor
CargoShip() : Ship() {
capacity = 0;
}
//Overloaded constructor for CargoShip, calls parent class
CargoShip(int tonnage, string name) : Ship() {
CargoShip::capacity = tonnage;
}
// Accessor Function
int getCapacity() const {
return capacity;
}
//Mutator Function
void setCapacity(int tonnage) {
cout << " Enter max capacity: " << endl;
cin >> tonnage;
tonnage = capacity;
}
//Overriding Print Function
virtual void print() const override{
cout << " Name: " << nameOfShip << endl;
cout << " Capacity: " << capacity << endl;
}
};
int main()
{
// Pointer Array for Ships, listing the 3 ship classes
Ship *shipArray[3] = { new Ship(), new CruiseShip(), new CargoShip() };
// For loop to print the data for each of the 3 ships
for (int i = 0; i < 3; i++)
{
shipArray[i]->print();
cout << endl;
}
// Stores new data using the mutator functions within the class
shipArray[0]->setShipName("RMS Titanic");
shipArray[0]->setShipYear(1909);
// Pointers to the derived class, stores new data for functions in CruiseShip class
CruiseShip *csPoint = static_cast<CruiseShip*>(shipArray[1]);
csPoint->setShipName("HMS Victory");
csPoint->setMaxPass(850);
// Pointer to the derived class, stores new data for functions in CargoShip class
CargoShip *cgPoint = static_cast<CargoShip*>(shipArray[2]);
cgPoint->setShipName("HMHS Britannic");
cgPoint->setCapacity(48158);
//For loop to re-display updated data using base class pointers
for (int i = 0; i < 3; i++) {
shipArray[i]->print();
cout << endl;
}
return 0;
}
For starters these data members
int yearBuilt;
string nameOfShip;
should have the access specifier protected instead of public.
In this constructor
Ship(int year, string name) {
Ship::yearBuilt = year;
Ship::nameOfShip = name;
year = 0;
name = "";
}
the last two statements are redundant and does not make sense. Define the constructor like
Ship( int year, const string &name ) : yearBuilt( year ), nameOfShip( name )
{
}
It will be better to define these getters
// Accessor Function for the year the ship was built
int getYearBuilt() const {
return yearBuilt;
}
// Accessor Function for the name of the ship
string getShipName() const {
return nameOfShip;
}
like
// Accessor Function for the year the ship was built
const int & getYearBuilt() const {
return yearBuilt;
}
// Accessor Function for the name of the ship
const string & getShipName() const {
return nameOfShip;
}
These setters do not make sense. For example arguments are not used. And moreover you are trying to reassign arguments with data members.
// Mutator Function to read input and set it to the value of yearBuilt
void setShipYear(int year) {
cout << " Enter Year: " << endl;
cin >> year;
year = yearBuilt;
cout << endl; // Spacing between printed data
}
// Mutator Function to read input and set it to the value of nameOfShip
void setShipName(string name) {
cout << " Enter Name: " << endl;
cin >> name;
name = nameOfShip;
cout << endl; // Spacing between printed data
}
they should be defined at least like
// Mutator Function to read input and set it to the value of yearBuilt
void setShipYear(int year) {
yearBuilt = year;
}
// Mutator Function to read input and set it to the value of nameOfShip
void setShipName(string name) {
nameOfShip - name;
}
This constructor
//Overloaded Constructor
CruiseShip(int maximum, int year, string name) : Ship() {
CruiseShip::passengersMAX = maximum;
}
does not initialize data members of the base class with the passed arguments. It should be defined like
//Overloaded Constructor
CruiseShip(int maximum, int year, const string &name) : Ship(year, name ), passengersMAX( maximum )
{
}
This setter
//Mutator
void setMaxPass(int maximum) {
cout << "Enter Passenger Max: " << endl;
cin >> maximum;
maximum = passengersMAX;
}
should be defined like
//Mutator
void setMaxPass(int maximum) {
passengersMAX = maximum;
}
This constructor
CargoShip(int tonnage, string name) : Ship() {
CargoShip::capacity = tonnage;
}
does not initialize with the argument the base class sub-object. Moreover the data member yearBuilt does not have a corresponding argument.
So at least the constructor should be defined like
CargoShip(int tonnage, string name) : Ship( 0, name ), capacity( tonnage )
{
}
This setter
//Mutator Function
void setCapacity(int tonnage) {
cout << " Enter max capacity: " << endl;
cin >> tonnage;
tonnage = capacity;
}
should be defined like
//Mutator Function
void setCapacity(int tonnage) {
capacity = tonnage;
}
In these declaration
CruiseShip *csPoint = static_cast<CruiseShip*>(shipArray[1]);
//...
CargoShip *cgPoint = static_cast<CargoShip*>(shipArray[2]);
you should use reinterpret_cast
CruiseShip *csPoint = reinterpret_cast<CruiseShip*>(shipArray[1]);
//...
CargoShip *cgPoint = reinterpret_cast<CargoShip*>(shipArray[2]);

private static variable accesing output is linker issues [duplicate]

This question already has answers here:
Undefined reference to static variable c++
(3 answers)
Closed 2 years ago.
I created a Class Student with instance data members
like studentname, studentaddress, studentrollno
i declared private static data member CollegeName that could be shared among all instances of class.
used promptfunction to take user input from the console
next functions to display student details.
Meanwhile resulting in below errors :
Meanwhile codes goes here:
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
int studentrollno;
string studentName;
string studentAddress;
static string CollegeName;
public:
void setRollNo(int rollno) {
studentrollno = rollno;
}
int getRollNo() {
return studentrollno;
}
void setName(string name) {
studentName = name;
}
string getName() {
return studentName;
}
void setAddress(string address) {
studentAddress = address;
}
string getAddress() {
return studentAddress;
}
static void setCollegeName(string collegename) {
CollegeName = collegename;
}
static string getCollegeName() {
return CollegeName;
}
void displayStudentDetails(); // member functions declare inside class Meanwhile it is defined
outside
static void show() {
cout << "this is static function " << endl;
}
};
// member functions define outside Student class
void Student :: displayStudentDetails() {
cout << "Student Name : " << getName() << " Student RollNo : " << getRollNo() << "Student Address
: " << getAddress() << "CollegeName: "<< getCollegeName() << endl;
}
void promptValues(Student &student) {
cout << "Enter the student Details " << endl;
cout << "Enter the details about student objects " << endl;
cout << endl;
int studentrollno;
string studentname , studentaddress ;
string collegename;
cout << "Enter the RollNo of the student " << endl;
cin >> studentrollno;
cout << "Enter the Name of the student " << endl;
cin >> studentname;
cout << endl;
cout << "Enter the address of the student " << endl;
cin >> studentaddress;
cout << endl;
cout << "Enter the collegeName of the student " << endl;
cin >> collegename;
student.setRollNo(studentrollno), student.setName(studentname), student.setAddress(studentaddress),
student.setCollegeName(collegename);
}
int main() {
Student student1, student2 , student3 , student4 , student5 ;
Student studentarrays[5] = { student1, student2, student3, student4, student5 };
Student studentmodel[5];
for (int i = 0; i < 5; i++) {
Student model;
model = studentarrays[i];
promptValues(model);
studentmodel[i] = model;
}
for (Student studentdetails : studentmodel) {
studentdetails.displayStudentDetails();
}
Student::show();
return 0;
}
You have omited the definition of the static member Student::CollegeName. It is only declared in the class, now you should define it after the class declaration with this:
std::string Student::CollegeName;
For more information see https://en.cppreference.com/w/cpp/language/static

Trying to sort Vector of Objects

As the title suggest, I am trying to sort a vector of objects by the GPA. My main issue is putting a method where I define the function for my comparison. The vector itself holds objects of five fields, which includes: string name, string ssn, string year, float credit, float gpa. I know theirs a way to use the sort operator. I am new to C++ so I am not very knowledgeable in this language. I appreciate the help! Here is the code:
#include <iostream>
#include <string>
#include <iterator>
#include <iomanip>
#include <fstream>
#include <vector>
#include <sstream>
#include <algorithm>
#include <cstdlib>
#include <list>
using namespace std;
class Student {
//declare local variables
protected:
string name; //people with names longer than 21 characters will just
have to make do
string ssn; // Social Secturity Number.
float gpa; //Most up to date gpa for the student
float credits; //Number of student's credit hours
//build public methods
public:
//Default Constructor
Student() {}
//Student constructor. Besides the character arrays, everything else is passed by reference.
Student(const string n, const string s, string sGPA, string sCredits) {
name = n;
ssn = s;
gpa = (float)atof(sGPA.c_str());
credits = (float)atof(sCredits.c_str());
}
string getName() {
return name;
}
string getSSN() {
return ssn;
}
float getGPA() {
return gpa;
}
float getCredit() {
return credits;
}
//a function that is expected to be implemented and overridden by subclasses
virtual void print() const {
cout << '\n' << endl;
cout << "Student's name: " << name << endl;
cout << "Student SSN: " << ssn << endl;
cout << "Student's current GPA: " << gpa << endl;
cout << "Student's credit hours: " << credits << endl;
}
// a pure virtual function for implementation later. Makes whole class Abstract
virtual float tuition() const = 0;
};
class Undergrad : public Student {
//declare local variables
protected:
float undergrad_rate = 380.0;
string year;
//build public methods
public:
//Default Constructor
Undergrad() {}
//Undergrad Constructor
Undergrad(const string n, const string s, string uGPA, string uCredits, string y) :
Student(n, s, uGPA, uCredits), year(y) {}
//Display the contents of undergrad
void print() const {
Student::print();
cout << "Undergrad Rate: " << undergrad_rate << endl;
cout << "Year: " << year << endl;
}
//Display undergrad's current year
string get_year() {
return year;
}
//Display the undergrad's current rate
float get_rate() {
return undergrad_rate;
}
//Set a undergrad's current year
void set_year(string y) {
year = y;
}
//Display the cost for an undergrad to attend university
float tuition() const {
return 1000000;
}
};
int main() {
ifstream ip("data.txt");
if (!ip.is_open()) std::cout << "ERROR: File not found" << '/n';
string name;
string ssn;
string year;
string credit;
string gpa;
list<Undergrad> myList;
list<Undergrad>::iterator i;
//Undergrad g(name, ssn, year, credit, gpa);
while (ip.good()) {
getline(ip, name, ',');
getline(ip, ssn, ',');
getline(ip, gpa, ',');
getline(ip, credit, ',');
getline(ip, year, '\n');
// float number = stoi(gpa);
//float number1 = stoi(credit);
Undergrad g(name, ssn, year, credit, gpa);
myList.push_back(g);
}
ip.close();
//This deletes the last object in the list and stores it in a temp object. It assigns that object to the beginning of the list.
Undergrad temp = myList.back();
myList.pop_back();
myList.insert(myList.begin(), temp);
/* for (int i = 0; i < myList.size(); i++) {
cout << "Name: " << myList[i].getName() << endl;
cout << "SSN: " << myList[i].getSSN() << endl;
cout << "Year: " << file[i].get_year() << endl;
cout << "Credit: " << file[i].getCredit() << endl;
cout << "GPA " << file[i].getGPA() << endl;
cout << " " << endl;
}
*/
/*for (Undergrad &x : myList) { //Goes through my list and displays its contents
x.print(); //This isn't bringing up errors.
}
*/
//This code copy the contents of the list to a vector.
std::vector<Undergrad> vect{ std::make_move_iterator(std::begin(myList)),
std::make_move_iterator(std::end(myList)) };
std::sort(vect.begin(), vect.end(), CompareGPA);
for (Undergrad &x : vect) {
x.print();
}
system("pause");
return 0;
}
Furthermore this is the code Im trying to implement to get the comparision
bool CompareGPA(const Student& left, const Student& right) {
return left.gpa > right.gpa;
}
Using lambda you can implement like this:Use a property int get_gpa() const to access the protected member.
std::sort(vect.begin(), vect.end(), [] (const Student& left, const Student& right)
{
return left.get_gpa() > right.get_gpa();
});
Here how to implement the property ( a member function to return the protected variable) :
int get_gpa() const
{
return gpa;
}

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

C++ I/O stream text file to array issue

My code is supposed to read 16 lines from a text file, and passing them into an array of 4 Objects, each with 4 attributes. The problem im encountering is that while everything seems to work fine on passing the text details to the array, the 1st array element of the last object in the array is not the one supposed to be! I am really stuck!
My code is :
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int CDsize;
class CD {
public:
// constructors
CD();
CD(string arist, string title, int year, double price);
// getter methods
string getArtist() const { return this->artist; }
string getTitle() const { return this->title; }
int getYear() const { return this->year; }
double getPrice() const { return this->price; }
// setter methods - inline functions
void setArtist(const string artist) { this->artist = artist; }
void setTitle(const string title) { this->title = title; }
void setYear(const int year) { this->year = year; }
void setPrice(const double price) { this->price = price; }
// option methods
private:
string artist;
string title;
int year;
double price;
};
/*Text menu option 1/*
void printallcds(CD MAX_CDS[])
{
int d;
for (d=0; d<=CDsize; d++)
{
cout << "CD Number : " << d << "/ Artist : " << MAX_CDS[d].getArtist() << "/
Title : " << cout << MAX_CDS[d].getTitle() << "/ Year of Release : " <<
MAX_CDS[d].getYear() << "/ Price : " <<
cout << MAX_CDS[d].getPrice() << endl;
}
}*/
int main() {
CD MAX_CDS[3];
int CDsize = (sizeof(MAX_CDS) / sizeof(MAX_CDS[0]));
ifstream CDfile("mystock.txt");
string data;
int yeardata;
double pricedata;
int i;
for (i = 0; i < 4; i++) {
getline(CDfile, data);
MAX_CDS[i].setArtist(data);
getline(CDfile, data);
MAX_CDS[i].setTitle(data);
getline(CDfile, data);
stringstream yearstream(data);
yearstream >> yeardata;
MAX_CDS[i].setYear(yeardata);
getline(CDfile, data);
stringstream pricestream(data);
pricestream >> pricedata;
MAX_CDS[i].setPrice(pricedata);
}
CDfile.close();
// testing
cout << MAX_CDS[3].getArtist() << endl; // error !!!
cout << MAX_CDS[3].getTitle() << endl;
cout << MAX_CDS[3].getYear() << endl;
cout << MAX_CDS[3].getPrice() << endl;
return 0;
}
// constructors implementation
CD::CD() {}
CD::CD(string artist, string title, int year, double price) {
this->artist = artist;
this->title = title;
this->year = year;
this->price = price;
}
}
You only have space for 3 items in MAX_CDS (see CD MAX_CDS[3];), yet you're referencing the 4th item in your error.
MAX_CDS[3] // Actually represents the 4th item
Counting starts from 0 in C++.
So, to reference the 3rd item, in your case the last item, use MAX_CDS[2] or MAX_CDS[CDSize-1].
cout << MAX_CDS[CDSize-1].getArtist() << endl;
cout << MAX_CDS[CDSize-1].getTitle() << endl;
cout << MAX_CDS[CDSize-1].getYear() << endl;
cout << MAX_CDS[CDSize-1].getPrice() << endl;
Rereading your question, you probably want more items!
CD MAX_CDS[4]; // Now you have 4 items available: indexed 0, 1, 2, and 3