I have a base class and a derived class, I am trying to implement a virtual load function to add an extra member engineSize to the SportCar class, it should load the basic car details included in the Car class i.e CarName, Colour etc but also include engineSize which is unique to the SportsCar class. But it does not seem to workout well. Below I have included my code. Currently, it just defaults to the details included in the default constructor i.e. "Unknown".
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Car
{
public:
Car();
virtual void Load(ifstream& carFile);
int LoadString(string filename);
protected:
string CarName;
int Age;
string Colour;
double Price;
int countUsers;
Car *ptrToCarList;
};
class SportsCar : public Car
{
public:
SportsCar();
virtual void LoadSports(ifstream& carFile);
int LoadString(string filename);
void display();
protected:
int engineSize;
SportsCar *ptrToSportsCarList;
int countUsers;
};
Car::Car()
{
CarName = "Unknown";
countUsers = 2;
}
void Car::Load(ifstream& carFile)
{
carFile >> CarName >> Age >> Colour >> Price;
}
int Car::LoadString(string filename)
{
ifstream inFile(filename);
if (!inFile)
{
cout << "Sorry, file not found" << endl;
return -1;
}
ptrToCarList = new Car[countUsers];
for (int i = 0; i < countUsers; i++)
{
ptrToCarList[i].Load(inFile);
}
inFile.close();
return 0;
}
void SportsCar::display()
{
cout << CarName << " " << Age << " " << Colour << " " << Price << " " <<engineSize <<endl;
}
void SportsCar::LoadSports(ifstream& carFile)
{
Car::Load(carFile);
carFile >> engineSize;
}
SportsCar::SportsCar() :Car()
{
}
int SportsCar::LoadString(string filename)
{
ifstream inFile(filename);
if (!inFile)
{
cout << "Sorry, file not found" << endl;
return -1;
}
ptrToSportsCarList = new SportsCar[countUsers];
for (int i = 0; i < countUsers; i++)
{
ptrToSportsCarList[i].LoadSports(inFile);
}
inFile.close();
return 0;
}
int main()
{
SportsCar example2;
example2.LoadString("sportsCarFile.txt");
example2.display();
return 0;
}