0

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;
}
BeginnerLK
  • 33
  • 1
  • 7
  • yes if it is virtual, you can override and call the parent to do the base stuff first and then do the extra things for the specific fields of the derived class. – Philip Stuyck Apr 12 '15 at 19:43

2 Answers2

3

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.

Philip Stuyck
  • 7,344
  • 3
  • 28
  • 39
2

"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;
    }
};
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190