I have a base class of cars and a load function, if I have a derived class, can I use the load function from the base class and add extra data members such as engine size for sports cars to be loaded from a file. Below is my function definition.
void Car::Load(ifstream& carFile)
{
carFile >> CarName >> Age >> Colour >> Price;
}
yes you can :
class Car{
public:
virtual void Load(ifstream& carFile);
}
it is important that the Load method is virtual.
class SportsCar : public Car{
public:
virtual void Load(ifstream& carFile);
private:
int engineSize;
}
Here the method is overriden, so you are using inheritance
SportsCar::Load(ifstream& carFile){
Car::Load(carFile);
carFile >> engineSize;
}
and above is the implementation.
"can I use the load function from the base class and add extra data members such as engine size for sports cars to be loaded from a file."
If the function is declared virtual
in class Car
you can override and extend it in the derived class
class Car {
public:
virtual void Load(istream& carFile);
};
class SportsCar : public Car {
public:
virtual void Load(istream& carFile);
private:
int EngineSize;
};
void SportsCar::Load(istream& carFile)
{
Car::Load(carFile);
carFile >> EngineSize;
}
Note I have used std::istream
in my code sample, since it's not relevant if the stream is coming from a file for these parts of code.
You probably need a discriminator for the car type in the file (std::istream
respectively), to decide which class actually should be instantiated:
class CarFactory {
public:
static Car* LoadCarFromStream(istream& carStream) {
string carType;
Car* carResult = nullptr;
if(carStream >> carType) {
if(carType == "Car") {
carResult = new Car();
}
else if(carType == "SportsCar") {
carResult = new SportsCar();
}
}
if(carResult) {
carResult->Load(carStream);
}
return carResult;
}
};